Skip to content
Advertisement

Java: Conditional Statement and relational Operators

I am struggling with the following task created by Jetbrains:

Given three natural numbers A, B, C. Determine if a triangle with these sides can exist. If the triangle exists, output the YES string, and otherwise, output NO. A triangle is valid if the sum of its two sides is greater than the third side. If three sides are A, B and C, then three conditions should be met.

  1. A + B > C
  2. A + C > B
  3. B + C > A

Sample Input 1:

3
4
5

Sample Output 1:

YES

Now, my code is following:

import java.util.Scanner;

class Main {
    public static void main(String[] args) {
        // put your code here
    
        Scanner scanner = new Scanner(System.in);
    
        int a = scanner.nextInt();
        int b = scanner.nextInt();
        int c = scanner.nextInt();
    
        boolean aCheck = b + c > a;
        boolean bCheck = a + c > b;
        boolean cCheck = a + b > c;
    
       if (aCheck || bCheck || cCheck) {
           System.out.println("YES");
       } else {
           System.out.println("NO");
       }
    }
}

Logically, everything seems correct, but I am getting errors on the Input

1 2 3

I am really not sure what i may have missed. Is my code incorrect?

Advertisement

Answer

The code if (aCheck || bCheck || cCheck) passes if aCheck is true because it is based on the OR operator, for the triangle to be viable you need all the checks to pass. You should use the AND operator:

if (aCheck && bCheck && cCheck)

This was proposed by @sleepToken, on the comments, however, if you use && instead of & it will fail as soon as some check is false.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement