-3

I'm simply trying to determine if the user has entered a YES or NO value (disregarding caps though, hence equalsIgnoreCase()). However, regardless of me entering YES or NO, the do-while doesn't break E.G.

public int addInformation() {
    final int YES = 1;
    final int NO = 0;
    String userDecision = "";

    try(Scanner scanner = new Scanner(System.in)) {
        System.out.println("Add Information Now? [YES/NO]");

        do {
            System.out.println("Please Enter YES or NO ");
            userDecision = scanner.nextLine();
        } while(!userDecision.equalsIgnoreCase("yes") |
                           !userDecision.equalsIgnoreCase("no"));
    }
    if(userDecision.equalsIgnoreCase("yes")) {
          return YES;
    }
    return NO;
}

I'm looking for the behavior of "while the input value is not equal to 'yes' OR 'no', ask for the data again". However my code suggests "disregard whatever is typed, let's just keep looping for fun..." Where did I go wrong, Stack? thanks

Windle
  • 1,385
  • 2
  • 14
  • 33
3alto
  • 189
  • 1
  • 9

2 Answers2

2

This condition

while (!userDecision.equalsIgnoreCase("yes") |
                       !userDecision.equalsIgnoreCase("no"))

is always true. Any string must be EITHER not equal to "yes" OR not equal to "no".

If you mean to check that the string is not equal to either, you mean this:

while (!userDecision.equalsIgnoreCase("yes") &&
                       !userDecision.equalsIgnoreCase("no"))
khelwood
  • 55,782
  • 14
  • 81
  • 108
2

Your condition is incorrect. You want to end the loop if either condition is false (so you need an and). Something like,

while(!userDecision.equalsIgnoreCase("yes") &&
                       !userDecision.equalsIgnoreCase("no"));
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249