Shahrokh Aryana
Shahrokh Aryana

Reputation: 49

Java - Yes/No Loop

System.out.println("\nWould you like to order some coffee, " + customerName + "? (y/n)");

char response = keyboard.next().charAt(0);
while (response != 'y' && response != 'n') {
  System.out.println("\nInvalid response. Try again.");
  response = keyboard.next().charAt(0);
} if (response == 'n') {
  System.out.println("\nCome back next time, " + customerName + ".");
} else if (response == 'y') {
  System.out.println("\nGreat! Let's get started.");

When I run this program and check to see which inputs work, I find that even when I type words starting with 'y' or 'n' the code does not output the error message but moves onto the rest of the program. Also, even if I type in 'Y' or 'N', it registers as an invalid response.

Upvotes: 1

Views: 15003

Answers (2)

Olimpiu POP
Olimpiu POP

Reputation: 5067

The issue is that you are checking only the first letter of the read string:

char response = keyboard.next().charAt(0)

You should read the whole string:

String response = keyboard.next()

And use it in the comparison. In order to ensure that also 'Y' and 'N' are considered valid, you can use the String.equalsIgnoreCase(String):

while (!"Y".equalsIgnoreCase(response) && "N".equalsIgnoreCase(response))

System.out.println("\nWould you like to order some coffee, " + customerName + "? (y/n)");

So, wrapping all together this would look like this:

String response = keyboard.next();

while (!"Y".equalsIgnoreCase(response) && "N".equalsIgnoreCase(response)) {
   System.out.println("\nInvalid response. Try again.");
   response = keyboard.next();
} 

if ("N".equalsIgnoreCase(response)) {
   System.out.println("\nCome back next time, " + customerName + ".");
} else if ("Y".equalsIgnoreCase(response)) {
   System.out.println("\nGreat! Let's get started.");
}

Upvotes: 0

Eran
Eran

Reputation: 393936

Your code only checks the first character of the input, so it's no wonder words starting with y or n are considered valid. You might want to compare the entire String :

String response = keyboard.next();
while (!response.equalsIgnoreCase("y") && !response.equalsIgnoreCase("n")) {
  System.out.println("\nInvalid response. Try again.");
  response = keyboard.next();
} 
if (response.equalsIgnoreCase("n")) {
  System.out.println("\nCome back next time, " + customerName + ".");
} else {
  System.out.println("\nGreat! Let's get started.");
}

Upvotes: 2

Related Questions