Reputation: 33
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
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
Reputation: 691715
inp != 1 || inp != 2
That condition is always 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
Reputation: 48258
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
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
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