0
Scanner input = new Scanner(System.in);
selection = input.nextInt();
while (selection != 1 || selection != 2 || selection != 3 || selection != 4){
    System.out.println("*");
    selection = input.nextInt(); 
}

无论我输入什么,上面的代码都会进入一个循环,它只会重复自己。我可能在某个地方犯了一个愚蠢的错误,但我可能因为睡眠不足而看不到它。欢迎任何帮助,谢谢。

所有的 or 符号都已更改为 && 符号,但它仍在循环?

4

3 回答 3

4

代替

while (selection != 1 || selection != 2 || selection != 3 || selection != 4)

经过

while (selection != 1 && selection != 2 && selection != 3 && selection != 4)

选择!= 1 || selection != 2 is alwaystrue becauseselection` 不能不是 1 也不是 2。

于 2013-01-26T22:51:16.060 回答
1

你的条件总是正确的。对于您选择的任何数字,它始终不是 1不是 2。1等于1,但它不等于 2,因此条件为真,同样 2 不等于 1,因此条件为真。每隔一个数都不等于 12,所以条件仍然成立。

于 2013-01-26T22:51:24.297 回答
1

while除非表达式为假,否则将执行该块。 selection != 1 || selection != 2总是正确的。

我想你想改变!===更好

while (0 < selection && selection <= 4)
于 2013-01-26T22:54:01.997 回答