返回错误值的简单java程序

blmhpbnm  于 2021-09-13  发布在  Java
关注(0)|答案(3)|浏览(224)

你好,我正在复习java练习。我有一个非常简单的程序:有两个int值,以及一个布尔变量。如果其中一个值为负值,另一个值为正值,则程序将返回true。但是,如果布尔变量为true,则程序只能在两个int值均为负值时返回true。
我已经用一堆int值对此进行了测试,但是一旦我给这个方法(1,-1)的值,以及布尔值设置为true,程序似乎就会崩溃。任何帮助或解释都将不胜感激。

public static void main(String[] args) {
        System.out.println(posNeg(1,-1,true));
    }

    public static String posNeg(int a, int b, boolean negative){
        if(negative && (a<0 && b<0)){
            return "true";
        }else if(!negative && (a<0 && b>0) || (a>0 && b<0)){
            return "true";
        }
        return "false";
    }
4jb9z9bj

4jb9z9bj1#

您的代码因以下原因而中断: && 优先。
|| 括号内的条件:

public static void main(String[] args) {
    System.out.println(posNeg(1,-1,true));
}

public static String posNeg(int a, int b, boolean negative){
    if(negative && (a<0 && b<0)){
        return "true";
    }else if(!negative && ((a<0 && b>0) || (a>0 && b<0))){
        return "true";
    }
    return "false";
}
t1rydlwq

t1rydlwq2#

&&具有比| |更高的优先级,因此在else if条件下,即!负&&(a<0&&b>0)| |(a>0&&b<0)首先计算此条件!负&&(a<0&&b>0),然后使用res | |(a>0&&b<0)对结果进行评估。
在你的例子中,我想你首先要计算| |,然后&,所以只需在括号中加上这样一个括号!负&&((a<0&&b>0)| |(a>0&&b<0)),因此首先计算括号内的条件,然后使用&&

public class Main
{
     public static void main(String[] args) {
        System.out.println(posNeg(1,-1,true));
    }

    public static String posNeg(int a, int b, boolean negative){
        if(negative && (a<0 && b<0)){
            return "true";
        }else if(!negative && ((a<0 && b>0) || (a>0 && b<0))){
            return "true";
        }
        return "false";
    }
}
2q5ifsrm

2q5ifsrm3#

public static void main(String[] args) {
    System.out.println(posNeg(1,-1,false));
}

公共布尔posneg(inta,intb,布尔负){if(负)返回(a<0&&b<0);else返回((a<0&&b>0)| |(a>0&&b<0));)

相关问题