简体   繁体   English

Java:条件语句和关系运算符

[英]Java: Conditional Statement and relational Operators

I am struggling with the following task created by Jetbrains:我正在努力完成 Jetbrains 创建的以下任务:

Given three natural numbers A, B, C. Determine if a triangle with these sides can exist.给定三个自然数 A、B、C。确定是否存在具有这些边的三角形。 If the triangle exists, output the YES string, and otherwise, output NO.如果三角形存在,则输出 YES 字符串,否则输出 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.如果三个边是A、B和C,那么应该满足三个条件。

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

Sample Input 1:样本输入 1:

3
4
5

Sample Output 1:样本输出 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 1 2 3

I am really not sure what i may have missed.我真的不确定我可能错过了什么。 Is my code incorrect?我的代码不正确吗?

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.如果 aCheck 为真,则代码if (aCheck || bCheck || cCheck)通过,因为它基于 OR 运算符,要使三角形可行,您需要通过所有检查。 You should use the AND operator:您应该使用 AND 运算符:

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.这是@sleepToken 在评论中提出的,但是,如果您使用&&而不是&它会在某些检查为假时立即失败。

Change the condition to: if (aCheck && bCheck && cCheck) {}将条件更改为: if (aCheck && bCheck && cCheck) {}

If you want to stick to ||如果你想坚持 || operator then change it to: if ( !(a+b<=c || b+c<=a || a+c<=b) ) {}运算符然后将其更改为: if ( !(a+b<=c || b+c<=a || a+c<=b) ) {}

Peace out!!安息吧!!

Please take a look at my code :请看一下我的代码:

import java.util.Scanner; 
class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        // start coding here
        int A = scanner.nextInt();
        int B = scanner.nextInt();
        int C = scanner.nextInt();
        if(A + B > C && A + C > B && B + C > A){
            System.out.println("YES");
        }
        else{
            System.out.println("NO");
        }
    }
}

you should use && instead of ||你应该使用&&而不是||

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM