Write a Java Program Code for this ???
TRIANGLE TYPE
Given the 3 angles of a triangle (in degrees), write a program
to determine whether it is a right triangle, isosceles triangle,
right isosceles tri
The Correct Answer and Explanation is :
Here’s a Java program that determines the type of triangle based on the three given angles:
import java.util.Scanner;
public class TriangleType {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Input the angles of the triangle
System.out.print("Enter the first angle: ");
int angle1 = scanner.nextInt();
System.out.print("Enter the second angle: ");
int angle2 = scanner.nextInt();
System.out.print("Enter the third angle: ");
int angle3 = scanner.nextInt();
// Validate the angles
if (angle1 + angle2 + angle3 != 180) {
System.out.println("The angles do not form a triangle.");
} else {
// Determine the type of triangle
if (angle1 == 90 || angle2 == 90 || angle3 == 90) {
System.out.println("This is a right triangle.");
} else if (angle1 == angle2 || angle2 == angle3 || angle1 == angle3) {
if (angle1 == 90 || angle2 == 90 || angle3 == 90) {
System.out.println("This is a right isosceles triangle.");
} else {
System.out.println("This is an isosceles triangle.");
}
} else {
System.out.println("This is a scalene triangle.");
}
}
scanner.close();
}
}
Explanation:
This Java program determines the type of triangle based on the angles provided by the user. The program follows these steps:
- Input Angles: It first prompts the user to enter three angles, which are stored in integer variables (
angle1,angle2,angle3). - Angle Validation: The program checks if the sum of the three angles equals 180 degrees, which is a fundamental property of triangles. If the sum is not 180, it indicates that the angles do not form a valid triangle.
- Triangle Type Determination:
- Right Triangle: The program checks if any of the angles are equal to 90 degrees. If so, it prints that the triangle is a right triangle.
- Isosceles Triangle: Next, it checks if any two angles are equal. If two angles are equal and one is 90 degrees, it identifies the triangle as a right isosceles triangle.
- If neither condition is met, the triangle is classified as scalene, meaning all angles are different.
- Output: Based on the checks, the program outputs the type of triangle.
This structured approach ensures clarity and correctness, making it easy for users to understand the properties of the triangle based on the angles they input.