Okay, so here is my code:
public static void playAgain(Scanner in){
System.out.print("Play again?: ");
String again=in.next();
if (again.equalsIgnoreCase("y")){
playerScore=0;
aiScore=0;
playAgain=true;
}
else if (again.equalsIgnoreCase("n")){
playAgain=false;
}
else {
while (!again.equalsIgnoreCase("y") && !again.equalsIgnoreCase("n")){
System.out.print("Invalid response. Please enter \"y\" or \"n\": ");
again=in.next();
}
}
}
For some reason, if I input the wrong variable, say ‘boog’, the while loop prints an error message but for some reason defaults to ‘y’ even if I input ‘n’ – for example, a sample run would be:
Play again? boog
Invalid input, please input y or n. n
-program plays again despite my inputting n-
How do I fix this? Is it something with the order? Thanks in advance!
It could be because you are not setting
playAgaintofalseafter exiting the while loop. Is the previous value ofplayAgaintrue?I think you need to think about refactoring so that the while loop is above the ‘y’ and ‘n’
if/elsestatement. That way theif/elseis always called once the user has entered a valid value. Validation should be at the start of the method.