jobravooo
jobravooo

Reputation: 33

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();
}

Upvotes: 0

Views: 63

Answers (5)

OneCricketeer
OneCricketeer

Reputation: 191743

Alternatively to the other answers with &&, you can pull out the negative because you want to check "while not any of those options", i.e. "not (this or that or somethingElse)"

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

}

Upvotes: 0

JB Nizet
JB Nizet

Reputation: 691715

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)

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

Upvotes: 0

zorg93
zorg93

Reputation: 39

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

Upvotes: 0

Abdelhak
Abdelhak

Reputation: 8387

Try to replace || with && like this:

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

Because the first condtion with || was always true.

Upvotes: 3

Related Questions