Java Program to calculate the perimeter of an equilateral triangle – In this particular piece, we will brief in on how to calculate the perimeter of an equilateral triangle.
Suitable examples and sample programs have been added for the better apprehension of the mentioned codes. The compiler has also been added with which you can execute the codes yourself.
The means of calculating the perimeter of an equilateral triangle in Java programming in this article are as follows:
- Using Scanner Class
- Using Command Line Arguments
- Using Static Function
An equilateral triangle, as we all know, is a triangle with all of its sides equal. Owing to the angle-side relationship, all the angles of an equilateral triangle are equal to 60 degrees.
This is how an equilateral triangle looks like:
As you can see, this is an equilateral triangle with a side length of “a” units.
The perimeter of an equilateral triangle can be calculated with this formula:
Perimeter = a + a + a = 3a
The altitude of an equilateral triangle bisects the opposite side in equal halves.
Thus, by applying Pythagoras Theorem, we can calculate the height to be [(sqrt3)/2]*a
So, the area of the triangle is:
Area = 1/2 * [(sqrt3)/2]*a * a = [(sqrt 3)/4]*a^2
Hence, the several ways to calculate the perimeter of an equilateral triangle in Java Programming are as follows:
Using Scanner Class
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
import java.util.Scanner; class PerimeterOfEquilateralTriangle { public static void main(String args[]) { Scanner s= new Scanner(System.in); System.out.println("Enter the side of the Triangle:"); double a= s.nextDouble(); double perimeter=3*a; System.out.println("perimeter of Triangle is: " + perimeter); } } |
1 2 |
Enter the side of the Triangle:6 perimeter of Triangle is: 18.0 |
Using Command Line Arguments
1 2 3 4 5 6 7 8 9 10 11 12 13 |
import java.util.Scanner; class PerimeterOfEquilateralTriangle1 { public static void main(String args[]) { double a= Double.parseDouble(args[0]); double perimeter=3*a; System.out.println("perimeter of Triangle is: " + perimeter); } } |
1 2 3 |
javac PerimeterOfEquilateralTriangle1.java java PerimeterOfEquilateralTriangle1 6 perimeter of Triangle is: 18.0 |
Using Static Function
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
import java.util.Scanner; class PerimeterOfEquilateralTriangle { public static void main(String args[]) { Scanner s= new Scanner(System.in); System.out.println("Enter the side of the Triangle:"); double a= s.nextDouble(); double perimeter=PerimeterOfCircle.area(a); System.out.println("perimeter of Triangle is: " + perimeter); } public static double area(double s1) { double a=3*s1; return s1; } } |
1 2 |
Enter the side of the Triangle:6 perimeter of Triangle is: 18.0 |