Problem a ( PA4a.java ) Write a program to evaluate the area of a triangle given
ID: 3755636 • Letter: P
Question
Problem a (PA4a.java)
Write a program to evaluate the area of a triangle given the lengths of its sides using Heron's Formula1.
Here is an outline:
1. Get the three side lengths from the user (which might have decimal values): a, b, c.
2. 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).
3. Calculate the semiperimeter (s):
4. 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
1 http://en.wikipedia.org/wiki/Heron%27s_formula
s =
a + b + c
2
area =
p
s(s _ a)(s _ b)(s _ c)
Explanation / Answer
code
==============================================
import java.util.*;
public class Example{
public static void main(String args[]){
double a,b,c;
double Per,area;
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the length of side a:");
a = scanner.nextInt();
System.out.println(" Enter the length of side b:");
b = scanner.nextInt();
System.out.println(" Enter the length of side c:");
c = scanner.nextInt();
if ((a + b > c) && (a + c > b) && (b + c > a))
{
System.out.println(" Sides are valid");
Per=perimeter(a,b,c);
System.out.println(" Perimeter of traingle is:"+Per);
area= area(Per,a,b,c);
double roundOff = Math.round(area*100.0)/100.0;
String.format("%.2f",roundOff);
System.out.println("Area of traingle is :"+roundOff);
}
else
{
System.out.println("The values entered by you are not valid");
}
}
public static double perimeter(double x,double y,double z)
{
double p=(x+y+z)/2;
return p;
}
public static double area(double s,double x,double y,double z)
{
double A=Math.sqrt((s*(s-x)*(s-y)*(s-z)));
return A;
}
}
[
==================================================================
Happy leraning
Comment for doubts
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.