简体   繁体   English

为什么这个while循环不终止? 比较整数

[英]Why is this while loop not terminating? Comparing ints

I am trying to create a sort of menu. 我正在尝试创建一种菜单。 And if none of the options in the menu are selected then it should keep repeating the options. 并且,如果菜单中的任何选项均未选中,则应继续重复这些选项。 However this while loop is not termintating and I'm not sure why. 但是,这个while循环不是终点,我不确定为什么。

I suspect it has something to do with how I am comparing my ints. 我怀疑这与我比较我的积分有关。

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

That condition is always true: 该条件始终为真:

  • if inp is 42, the first operand is true and the second as well, so the result is true 如果inp为42,则第一个操作数为true,第二个操作数也为true,因此结果为true
  • if inp is 1, the first operand is false and the second is true, so the result is true 如果inp为1,则第一个操作数为false,第二个为true,因此结果为true
  • if inp is 2, the first operand is true and the second is false, so the result is true 如果inp为2,则第一个操作数为true,第二个为false,因此结果为true

You want && , not || 您要&&而不是|| .

Or you could also use 或者你也可以使用

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

Or simpler: 或更简单:

while (inp < 1 || inp > 4)

Try to replace || 尝试替换|| with && like this: &&像这样:

  while(inp != 1 && inp != 2 && inp != 3 && inp != 4 ){

Because the first condtion with || 因为第一个条件是|| was always true. 永远是真的。

You need to use && for the checking. 您需要使用&&进行检查。 no matter what is input at least 3 of the 4 or statements will be true, therefore the loop will loop again 无论输入什么,至少4个中的3个或语句为true,因此循环将再次循环

Alternatively to the other answers with && , you can pull out the negative because you want to check "while not any of those options", ie " not (this or that or somethingElse)" 除了使用&&的其他答案之外,您还可以拉出否定的答案,因为您想检查“同时不选择任何选项”,即“ (此那个其他东西)”

while (!(inp == 1 || inp == 2 || inp == 3 || inp == 4))) {

}

Your condition is wrong formulated, 您的情况表述错误,

this: 这个:

while (inp != 1 || inp != 2 || inp != 3 || inp != 4) {

must be replaced by 必须替换为

while (inp != 1 && inp != 2 && inp != 3 && inp != 4) {

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM