Tag Archives: heron’s formula

Java program to calculate area of a triangle(Hero’s formula)

This is a Java Program to Find the Area of a Triangle Given Three Sides.Enter the length of three sides of triangle. Now we use the Heron’s formula to get the area of triangle.

In geometry, Heron’s formula also called Hero’s formula),  gives the area of a triangle by requiring no arbitrary choice of side as base or vertex as origin, contrary to other formulas for the area of a triangle, such as half the base times the height or half the norm of a cross product of two sides.

A = \sqrt{s(s-a)(s-b)(s-c)},

where s is the semiperimeter of the triangle; that is,

  s=\frac{a+b+c}{2}.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.text.DecimalFormat;

public class CalcTriangleArea {
    public static void main(String[] args) {
        InputStreamReader isr = new InputStreamReader(System.in);
        BufferedReader br = new BufferedReader(isr);
        try {
            System.out.println("Enter side1:");
            String input = br.readLine();
            double a = Double.parseDouble(input);
            System.out.println("Enter side2:");
            input = br.readLine();
            double b = Double.parseDouble(input);
            System.out.println("Enter side3:");
            input = br.readLine();
            double c = Double.parseDouble(input);
            DecimalFormat df = new DecimalFormat("0.00");
            System.out.println("You Entered:" + a + " " + b + " " + c);
            if ((a + b) > c && (b + c) > a && (a + c) > b) {
                double s = (a + b + c) / 2;
                double area = Math.sqrt((s * (s - a) * (s - b) * (s - c)));
                System.out.println("Area:" + df.format(area));
            } else {
                System.out.println("Can't form a triangle with the gives side..");
            }

        } catch (Exception e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
        }
    }
}