In my java code below:
while(true) {
userResponse = keyboard.nextLine();
if(userResponse.length() == 1 && userResponse.charAt(0) == 'y') {
break;
}
else if(userResponse.length() == 1 && userResponse.charAt(0) == 'n') {
System.out.println("Come back next time " + userName + ".");
System.exit(0);
}
else {
System.out.println("Invalid response.");
}
}
Before the loop is entered the block of code:
else {
System.out.println("Invalid response.");
}
is executed. Can someone point out why this is happening or whats wrong?
Edit: The keyboard Scanner is used before in this block of code as well
while(true) {
userResponse = keyboard.nextLine();
if(userResponse.length() == 1 && userResponse.charAt(0) == 'y') {
System.out.println("Great! Let's get started.");
break;
}
else if(userResponse.length() == 1 && userResponse.charAt(0) == 'n') {
System.out.println("Come back next time " + userName + ".");
System.exit(0);
}
else {
System.out.println("Invalid response.");
}
}
Thanks for the replies, I fixed it by replacing "keyboard.nextLine();" with "keyboard.next();"