[英]Why is this while loop not terminating? Comparing ints
我正在尝试创建一种菜单。 并且,如果菜单中的任何选项均未选中,则应继续重复这些选项。 但是,这个while循环不是终点,我不确定为什么。
我怀疑这与我比较我的积分有关。
Scanner s = new Scanner(System.in);
int inp = s.nextInt();
while (inp != 1 || inp != 2 || inp != 3 || inp != 4) {
System.out.println("Not one of the options");
System.out.println("Please choose an option:");
System.out.println("\t1) Edit Property");
System.out.println("\t2) View More info on Property");
System.out.println("\t3) Remove Property");
System.out.println("\t4) Return");
s = new Scanner(System.in);
inp = s.nextInt();
}
inp != 1 || inp != 2
该条件始终为真:
您要&&
而不是||
。
或者你也可以使用
while (!(inp == 1 || inp == 2 || inp == 3 || inp == 4))
或更简单:
while (inp < 1 || inp > 4)
尝试替换||
与&&
像这样:
while(inp != 1 && inp != 2 && inp != 3 && inp != 4 ){
因为第一个条件是||
永远是真的。
您需要使用&&进行检查。 无论输入什么,至少4个中的3个或语句为true,因此循环将再次循环
除了使用&&
的其他答案之外,您还可以拉出否定的答案,因为您想检查“同时不选择任何选项”,即“ 不 (此或那个或其他东西)”
while (!(inp == 1 || inp == 2 || inp == 3 || inp == 4))) {
}
您的情况表述错误,
这个:
while (inp != 1 || inp != 2 || inp != 3 || inp != 4) {
必须替换为
while (inp != 1 && inp != 2 && inp != 3 && inp != 4) {
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.