In: Computer Science
Java Question:
Write three static functions that each take two double values which represent the two smaller sides of a right triangle. The first will calculate and return the area of the triangle, the second will calculate and return the length of the hypotenuse and the third will calculate and return the perimeter of the triangle. (Note: to calculate the perimeter, you need the value of the hypotenuse, so you must be calling that method from inside the other method.) You will also create a main method to ask the user to give the two inputs for a triangle. Then report the results of calls to the three methods. Important: None of these methods should output the results to the screen, all input and output should be done in the main. Additionally the user should be allowed to input multiple sets of data until they decide that they are finished. (Formulas for triangles are easily found on the internet, but I can provide them for you if you can’t find them.)
If you can put comments on lines to explain codes, it would be much appreciated! Thanks!
import java.util.*;
import java.lang.Math;
public class Main
{
public static double getArea(double a,double b)
{
//right triangle area formula is 0.5*base*height;
return 0.5*a*b;
}
public static double getHypotenuse(double a,double b)
{
//hypotenuse formula is Square root(a*a+b*b)
return Math.sqrt(a*a+b*b);
}
public static double getPerimeter(double a,double b)
{
//perimeter is a+b+c
return a+b+getHypotenuse(a,b);
}
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
double a,b,c,area,perimeter;
String ch;
//we use a do while loop and continue until user wants
to exit
do
{
System.out.print("Enter the first
side: ");
a=s.nextDouble();
System.out.print("Enter the second
side: ");
b=s.nextDouble();
area=getArea(a,b);
c=getHypotenuse(a,b);
perimeter=getPerimeter(a,b);
System.out.println("First Side:
"+a);
System.out.println("Second Side:
"+b);
System.out.println("Hypotenuse:
"+c);
System.out.println("Area:
"+area);
System.out.println("Perimeter:
"+perimeter);
System.out.print("Do you want to
continuue?(y/n): ");
ch=s.next();
}while(ch.equals("y"));
}
}