简体   繁体   中英

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.

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
  • if inp is 1, the first operand is false and the second is true, so the result is true
  • if inp is 2, the first operand is true and the second is false, so the result is 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

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) {

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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