小编Pau*_*aul的帖子

使用较短版本或"||" 在带有整数和数学/逻辑错误的If语句中?

所以我终于得到了我的代码:

if((choice == 1 ) || (choice == 2) || (choice == 3) || (choice == 4)){
Run Code Online (Sandbox Code Playgroud)

但为什么:

if(choice == (1 | 2)) {
Run Code Online (Sandbox Code Playgroud)

导致逻辑/数学错误?例如,如果我输入"3",则代码接受它并将其处理为成功.代码段如下:

while(counter == 0){
        try{
            int choice = Integer.parseInt(input.nextLine());

            if(choice == (1 | 2)){
                System.out.println("You got it!");
                ++counter;
            }else{
                System.out.println("Try again");
            }
        }
        catch(NumberFormatException Exception){
            System.out.println("You did something wrong");
        }


    }
Run Code Online (Sandbox Code Playgroud)

如果我这样做:

if(choice == (1 | 2 | 3 | 4 )){
Run Code Online (Sandbox Code Playgroud)

那么就我所知,它只会接受7.在编译时到底发生了什么,是否有办法缩短我找到的解决方案?

java if-statement

2
推荐指数
1
解决办法
113
查看次数

标签 统计

if-statement ×1

java ×1