Find area of triangle (three sides) using hero formula ( java & example)
Yogesh
Given three sides of triangle, find the area of triangle using hero’s formula.
Suppose a, b and c are the sides of triangle.
We will read the input from console using Scanner class.
1. Algorithm: find area of triangle using hero’s formula in java (example)
Read the sides of triangle from console.
Check given sides of triangle can form a valid triangle.
Any two sides of a triangle should be greater than third side.
If yes, We will find out the area of triangle.
Find the semi perimeter of triangle.
semiPerimeter = (a+ b + c)/2
Find out the area of triangle using semi perimeter
Area = sqrt(s(s-a)(s-b)(s-c))
2. Program: calculate area of triangle using hero formula in java (example)
package org.learn;
import java.util.Scanner;
public class AreaOfTriangleHero {
public static void main(String[] args) {
try (Scanner scanner = new Scanner(System.in)) {
System.out.printf("Enter length of first side of triangle : ");
double side1 = scanner.nextDouble();
System.out.printf("Enter length of second side of triangle : ");
double side2 = scanner.nextDouble();
System.out.printf("Enter length of third side of triangle : ");
double side3 = scanner.nextDouble();
boolean isValidTriangle = (side1 + side2) > side3 && (side1 + side3) > side2 &&
(side1 + side3) > side2;
if(!isValidTriangle) {
System.out.println("Side of triangle are invalid");
return;
}
//semiPerimeter s = (a+b+c) / 2
//where a,b,c are sides of triangle
double semiPerimeter = (side1 + side2 + side3)/2;
//Area = sqrt(s(s-a)(s-b)(s-c))
double area = Math.sqrt(semiPerimeter*(semiPerimeter-side1)
*(semiPerimeter-side2)*(semiPerimeter-side3));
System.out.printf("Area of triangle is : %4.2f",area);
}
}
}
3. Output: Area of triangle using hero’s formula in java (example).
1. Enter length of first side of triangle : 5
2. Enter length of second side of triangle : 6
3. Enter length of third side of triangle : 12
4. Sides of triangle are invalid
1. Enter length of first side of triangle : 4
2. Enter length of second side of triangle : 8
3. Enter length of third side of triangle : 10
4. Area of triangle is : 15.20
1. Enter length of first side of triangle : 5
2. Enter length of second side of triangle : 7
3. Enter length of third side of triangle : 10
4. Area of triangle is : 16.25