-4
$\begingroup$

Even though the input I type is a "Y" or "N" string, I can't break out if this while loop. Can anyone tell me why?

public String yesOrNo(String message) {
    String yesOrNo;

    do {
        System.out.print(message);
        yesOrNo = input.next(); 
    } while(yesOrNo != "N" || yesOrNo != "Y");
    
    return yesOrNo;
}
$\endgroup$
2
  • 1
    $\begingroup$ If yesorno is N then the second condition is true. If it is Y then the first condition is true. If neither then both conditions are true. The OR is always true. You want AND. Plus of course != or == compares pointers, and the pointers will never be equal. $\endgroup$
    – gnasher729
    Sep 25 at 13:39
  • $\begingroup$ @gnasher729, I would be careful with "the pointers will never be equal". It's not unreasonable to imagine a JVM implementation that uses singletons for single-character strings. $\endgroup$
    – Dmitry
    Sep 25 at 23:48
0
$\begingroup$

As indicated in the comments by gnasher729, you have made a mistake in your logic.

Your logic is as follows:

Input A: Input != "N" B: Input != "Y" A∨B (OR)
Y TRUE FALSE TRUE
N FALSE TRUE TRUE
Anything Else TRUE TRUE TRUE

The logic you want:

Input A: Input != "N" B: Input != "Y" A∧B (AND)
Y TRUE FALSE FALSE
N FALSE TRUE FALSE
Anything Else TRUE TRUE TRUE

In your code change or OR to be an AND to match the logic expressed above:

while(yesOrNo != "N" && yesOrNo != "Y");
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.