C Programs Tutorials | IT Developer
IT Developer

Java Programs



Share with a Friend

Operators & Expressions

Java Program: Validate Triangle Using Sum of Angles

Triangle Validity Rule

A triangle is valid if and only if:

  • Each angle > 0
  • Sum of all three angles = 180°

import java.util.Scanner;

 

public class TriangleValidation {

    public static void main(String[] args) {

 

        Scanner sc = new Scanner(System.in);

 

        System.out.print("Enter first angle: ");

        int a = sc.nextInt();

 

        System.out.print("Enter second angle: ");

        int b = sc.nextInt();

 

        System.out.print("Enter third angle: ");

        int c = sc.nextInt();

 

        System.out.println("\n------ Triangle Validation ------");

 

        if (a > 0 && b > 0 && c > 0 && (a + b + c) == 180) {

            System.out.println("The triangle is VALID.");

        } else {

            System.out.println("The triangle is NOT VALID.");

        }

 

        sc.close();

    }

}

Output

 
OUTPUT 1:

INPUT : 
Enter first angle: 60
Enter second angle: 60
Enter third angle: 60

OUTPUT : 
------ Triangle Validation ------
The triangle is VALID.


OUTPUT 2:

INPUT : 
Enter first angle: 90
Enter second angle: 45
Enter third angle: 45

OUTPUT : 
------ Triangle Validation ------
The triangle is VALID.
 
OUTPUT 3:

INPUT : 
Enter first angle: 0
Enter second angle: 90
Enter third angle: 90

OUTPUT : 
------ Triangle Validation ------
The triangle is NOT VALID.

Explanation

1. Input Angles

int a = sc.nextInt();

int b = sc.nextInt();

int c = sc.nextInt();

  • Reads three angles of the triangle.

2. Triangle Validation Condition

if (a > 0 && b > 0 && c > 0 && (a + b + c) == 180)

a > 0 && b > 0 && c > 0
Ensures no angle is zero or negative.

(a + b + c) == 180
Checks triangle angle sum rule.

3. Logical Operators Used

Operator

Purpose

&&

Logical AND

Comparison

==

Equality