Write a program in JAVA to evaluate the area of a triangle given the lengths of
ID: 3767104 • Letter: W
Question
Write a program in JAVA to evaluate the area of a triangle given the lengths of its sides using Heron's Formula[1]. Here is an outline:
Get the three side lengths from the user (which might have decimal values): a, b, c.
Check to ensure that the sides are valid for a triangle. Importantly, the sum of the lengths of any two sides must be larger than the length of the third side (you must check all three sides this way).
Calculate the semiperimeter (s):
Calculate the area:
You must format the output to have two decimal places (even if they are both 0), and round if necessary. For example:
Enter the length of side a: 3
Enter the length of side b: 4
Enter the length of side c: 5
The area is 6.00
Explanation / Answer
import java.util.Scanner;
/**
* @author Srinivas Palli Calculates area of triangle in Java given its 3 sides.
*/
public class TriangleArea {
/**
* @param args
*/
public static void main(String[] args) {
Scanner sn = new Scanner(System.in);
System.out.print("Enter the length of side a:");
double a = sn.nextDouble();
System.out.print("Enter the length of side b:");
double b = sn.nextDouble();
System.out.print("Enter the length of side c:");
double c = sn.nextDouble();
if (isTriangleValid(a, b, c)) {
double area = calculateArea(a, b, c);
System.out.printf("the Area is %.2f", area);
} else {
System.out.println("Sides entered cannot form a triangle!");
}
}
/**
* Calculates area of a triangle using length of its 3 sides
*/
static double calculateArea(double a, double b, double c) {
double p = (a + b + c) / 2;
return Math.sqrt(p * (p - a) * (p - b) * (p - c));
}
/**
* Checks whether the 3 sides can form a triangle The sum of any two sides
* must be greater than the other side
*
* @param a
* @param b
* @param c
* @return
*/
static boolean isTriangleValid(double a, double b, double c) {
if ((a + b) > c && (a + c) > b && (b + c) > a) {
return true;
} else {
return false;
}
}
}
OUTPUT:
Enter the length of side a:3
Enter the length of side b:4
Enter the length of side c:5
the Area is 6.00
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.