Description
This basic java example source code reads height and base of a rectangle from console input and then calculate the area and perimeter.
Right Triangle Area and Perimeter Source Code
The formula in calculating the area of a triangle is A = 1/2 base * height while Perimeter = base + height + hypotenuse. From this example we are asking for a user input of base and height. The area can easily be calculated using direct substitution, however the perimeter would be harder since we are missing the value of hypotenuse. From Pythagorean theorem, the hypotenuse of a right triangle can be calculate using the formula hypotenuse2 = b2 + height2
package com.javatutorialhq.java.examples;
import java.util.Scanner;
/*
* This example source code demonstrates how
* to calculate area and perimeter of a right
* triangle
*/
public class TriangleAreaPerimeterExample {
public static void main(String[] args) {
// read user input using scanner
Scanner s = new Scanner(System.in);
// ask from console the base of triangle
System.out.print("Enter the Base:");
// assign to a variable the user input
Double base = s.nextDouble();
// ask from console the height of triangle
System.out.print("Enter the height:");
// assign to a variable the user input
Double height = s.nextDouble();
// calculate the area
Double areaTriangle = 0.5 * base * height;
// calculate the hypotenuse
Double hypotenuse = Math.pow(Math.pow(base, 2)
+ Math.pow(height, 2),0.5);
// calculate the Perimeter
Double perimeter = base + height + hypotenuse;
// printing the area and perimeter
System.out.println("Area of triangle = "
+ areaTriangle);
System.out.println("Perimeter of triangle = "
+ perimeter);
s.close();
}
}
Sample Output
Enter the Base:98.25 Enter the height:78 Area of triangle = 3831.75 Perimeter of triangle = 301.69744915700755