[英]While loop not breaking out
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符号已更改为&&符号,但仍然不断循环播放?
更换
while (selection != 1 || selection != 2 || selection != 3 || selection != 4)
通过
while (selection != 1 && selection != 2 && selection != 3 && selection != 4)
选择!= 1 || 选择!= 2 is always
true, because
选择不能为1或2。
您的情况永远是正确的。 对于任何号码,你挑,它总是不为1 或 2,没有1 等于 1,但它不等于2,所以条件为真,同样2不等于1,因此条件为真。 每隔一个数字不等于1 或 2,因此条件仍然成立。
while
将执行该块,除非表达式为false。 selection != 1 || selection != 2
selection != 1 || selection != 2
始终为true。
我认为您想将!=
更改为==
或更好
while (0 < selection && selection <= 4)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.