Sum All Three Angles and Check Equal or Not in Java


Write a program to check whether a triangle is valid or not, when the three angles of the triangle are entered through the keyboard. A triangle is valid if the sum of all the three angles is equal to 180 degrees


The program starts by creating a Scanner object to read input from the user. It then prompts the user to enter the length of each side of the triangle using the nextInt() method of the Scanner class.

Next, the program calculates the sum of all angles in the triangle by adding the lengths of its sides. According to the triangle angle sum theorem, the sum of all angles in a triangle is always 180 degrees.

After calculating the sum of all angles, the program checks whether it is equal to 180 using an if-else statement. If the sum is equal to 180, it prints "Triangle is valid". Otherwise, it prints "Triangle is not valid".

It's worth noting that this program checks only the validity of the triangle based on the sum of angles being 180. However, a triangle is considered valid only if its sides fulfill the triangle inequality theorem, which states that the sum of the lengths of any two sides of a triangle must be greater than the length of the remaining side. Therefore, the program does not ensure that the lengths entered form a valid triangle based on this theorem.

Source Code

import java.util.Scanner;
class SumAll_Angles
{
	public static void main(String[] args)
	{
		Scanner input = new Scanner(System.in);
		System.out.print("Enter Triangle Side 1 :");
		int s1 = input.nextInt();
		System.out.print("Enter Triangle Side 2 :");
		int s2 = input.nextInt();
		System.out.print("Enter Triangle Side 3 :");
		int s3 = input.nextInt();
		int sum = s1 + s2 + s3; 
		if(sum == 180) 
		{
			System.out.println("Triangle is valid");
		}
		else
		{
			System.out.println("Triangle is not valid");
		}
	}
}

Output

Enter Triangle Side 1 :56
Enter Triangle Side 2 :63
Enter Triangle Side 3 :45
Triangle is not valid

Example Programs