a == b 的替代方法,没有布尔值

Alternative way to a == b, without boolean

我做了一个简单的程序。我想在用户输入“5”时停止它。

相关代码:

do { 
   System.out.println("Enter 5 to quit");    
   a = scanner.nextInt();     
   b = a==5;     
} while (b = true);

当然早些时候我命名了变量(int a、boolean b 等)

为什么我输入时它不起作用:

}while (b ==5)

PS。有没有办法重构代码(while改成for)?

如果输入 5 可以让您跳出循环,您的条件应该是:

do {
    ...
} while (!b); // or while (b == false)

while (b == true)while (a == 5) 只会在输入 5 时让您进入循环。

do { 
   System.out.println("Enter 5 to quit");     
} while (scanner.nextInt() != 5);

做的时候

}while (b = true);

您正在将 true 的值分配给 b,因此它将始终为真

你想要的是

}while (b != true);

}while (!b);

while (b = true);

you are using = here (assignment) in place of == (relational)

then you used this : b = a==5; now as per operator precedence, first a==5 will be executed which may return true or false.

this wont work : while (b ==5) as it is not identical to while (b ==true) in Java, In C/C++, true is any nonzero value and false is zero. In Java, true and false are nonnumeric values that do not relate to zero or nonzero.

so, you can try :

while (b == true);

while (a!=5);

虽然您需要阅读 java 的基础知识,但让我来回答您的问题

} while (b == 5);

行不通。这是因为您正在尝试将布尔值(您说您已将 b 声明为布尔值)与 5(整数)进行比较。