-1

I have a method here that is supposed to check if a user has entered a "y", pertaining to the answer yes; or an "n" pertaining to the answer no. It reads in the letters entered by the user correctly, however it keeps saying that the user has not entered a "y" or an "n". If someone could let me know what I'm doing wrong that would be great. Here is the code I'm using :

String answer = "";
do {
 while (answer.equals("")) {
  answer = sc.nextLine();
 }
 if (!answer.equals("y") || !answer.equals("n")) {
  System.out.println("Please enter a y, meaning yes; or an n, meaning no.");
  answer = "";
 }
} while (!answer.equals("y") || !answer.equals("n"));
vindev
  • 2,240
  • 2
  • 13
  • 20
Rei
  • 3
  • 3
  • Why do you think it wont? when you enter "y", you set answer as "y" but when you press entry for empty line then your answer becomes "" and you come out of while loop. – SMA Jan 27 '18 at 16:36
  • If you enter "n", then !answer.equals("y") is true, so the `or` condition is true. If you enter "y", then !answer.equals("n") is true, so the `or` condition is true. If you enter anything else, both conditions are true, so the `or`condition is true. – JB Nizet Jan 27 '18 at 16:41

1 Answers1

0

The answer is pretty simple, change your || to &&. This is, because every input is not equal to n or y.

The corrected code should look like this:

String answer = "";
Scanner sc = new Scanner(System.in);    
do {
    while(answer.equals("")) {
        answer = sc.nextLine();
    }
    if(!answer.equals("y") && !answer.equals("n")) {
        System.out.println("Please enter a y, meaning yes; or an n, meaning no.");
        answer = "";
    }
}while (!answer.equals("y") && !answer.equals("n"));
Thomas Böhm
  • 1,456
  • 1
  • 15
  • 27