Java 在 do while 循环中不等于
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26553579/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Not equal to in a do while loop
提问by user2650277
For some reason a sentinel value will not work as expected
由于某种原因,哨兵值不会按预期工作
public static int play() {
String input;int result;
do {
input = JOptionPane.showInputDialog("Do you want to play-Enter 1 if yes , 0 if no");
result = Integer.parseInt(input);
} while (result != 1 || result != 0);
return result;
}
This code above never works but it works just fine if i change the condition from while (result != 1 || result != 0);
to while (result < 0 || result > 1);
上面的代码从不工作,但如果我将条件从 更改while (result != 1 || result != 0);
为while (result < 0 || result > 1);
Why is that so and how can i make not equal work in a do...while
loop in java ?
为什么会这样,我如何才能do...while
在 java的循环中进行不相等的工作?
Thanks
谢谢
采纳答案by Victor2748
Use:
用:
while (result != 1 && result != 0) {...}
This will execute the code, ONLY if result
is NOT 0
or 1
这将执行代码,仅当result
不是0
或1
In your example, the boolean statement in the while
loop will ALWAYS be equal to true
because result can be equal to only 1 value:
在您的示例中,while
循环中的布尔语句将始终等于,true
因为结果只能等于 1 个值:
while (result != 0 || result != 1)
If result
is 1
, then it is not equal to 0
, if it is 0
, then it can't be 1
, so it will ALWAYS be true
如果result
是1
,那么它不等于0
,如果是0
,那么它不可能是1
,所以它永远是true
回答by Peadar ó Duinnín
while (result != 1 || result != 0)
while (result != 1 || result != 0)
This condition means it will always loop even with '1' or '0' as a response:
这种情况意味着即使使用“1”或“0”作为响应,它也将始终循环:
If the user enters 0, which should be valid, it will satisfy result != 1
and return true
.
如果用户输入 0,这应该是有效的,它将满足result != 1
并返回true
。
If the user enters 1, which should be valid, it will satisfy result != 0
and return true
.
如果用户输入 1,这应该是有效的,它将满足result != 0
并返回true
。
You need to use while (result != 1 && result != 0)
.
您需要使用while (result != 1 && result != 0)
.
This will loop only if the answer is both not equals to 1 and not equals to 0.
仅当答案既不等于 1 又不等于 0 时才会循环。