Answer:
The java program is as follows.
import java.lang.*;
public class Triangle
{
//variables to hold sides of a triangle
static double height;
static double base;
static double hypo;
//method to compute hypotenuse
static double rightTriangle(double h, double b)
{
return Math.sqrt(h*h + b*b);
}
public static void main(String[] args) {
height = 4;
base = 3;
hypo = rightTriangle(height, base);
System.out.printf("The hypotenuse of the right-angled triangle is %.4f", hypo);
}
}
OUTPUT
The hypotenuse of the right-angled triangle is 5.0000
Explanation:
1. The variables to hold all the three sides of a triangle are declared as double. The variables are declared at class level and hence, declared with keyword static.
2. The method, rightTriangle() takes the height and base of a triangle and computes and returns the value of the hypotenuse. The square root of the sum of both the sides is obtained using Math.sqrt() method.
3. The method, rightTriangle(), is also declared static since it is called inside the main() method which is a static method.
4. Inside main(), the method, rightTriangle() is called and takes the height and base variables are parameters. These variables are initialized inside main().
5. The value returned by the method, rightTriangle(), is assigned to the variable, hypo.
6. The value of the hypotenuse of the triangle which is stored in the variable, hypo, is displayed to the user.
7. The value of the hypotenuse is displayed with 4 decimal places which is done using printf() method and %.4f format specifier. The number 4 can be changed to any number, depending upon the decimal places required.
8. In java, all the code is written inside a class.
9. The name of the program is same as the name of the class having the main() method.
10. The class having the main() method is declared public.
11. All the variables declared outside main() and inside another method, are local to that particular method. While the variables declared outside main() and inside class are always declared static in java.