Triangle Validity Check in Java

Check if three sides can form a valid triangle using triangle inequality.

BeginnerModule 2: Conditional ProgramsExample 13 of 20
triangle-validity-check.java
1import java.util.Scanner;
2
3public class Main {
4 public static void main(String[] args) {
5 Scanner sc = new Scanner(System.in);
6
7 System.out.print("Enter side a: ");
8 int a = sc.nextInt();
9 System.out.print("Enter side b: ");
10 int b = sc.nextInt();
11 System.out.print("Enter side c: ");
12 int c = sc.nextInt();
13
14 if (a + b > c && a + c > b && b + c > a) {
15 System.out.println("Triangle is Valid");
16 } else {
17 System.out.println("Triangle is Not Valid");
18 }
19
20 sc.close();
21 }
22}

Output

Enter side a: 3
Enter side b: 4
Enter side c: 5
Triangle is Valid

What's going on

We use the triangle inequality theorem: sum of any two sides must be greater than the third side.