I'm making a very simple "guessing game" in Java. At the end of my game, I ask the user if he/she wants to play my game again as follows:
System.out.println("Would you like to play again? (Type 'yes' or 'no' into the field)");
Scanner scanner2 = new Scanner(System.in);
String again = scanner2.nextLine();
if (again=="yes") {
local = false;
loopAgain = true;
}
else if (again=="no") {
loopAgain = false;
local = false;
}
else {
System.out.println("Invalid input. Please type 'yes' or 'no' into the field.");
local = true;
}
Theoretically, if I type "yes" into the console, the if statement should execute, setting the variable loopAgain
to true which activates a while statement earlier in my code. The other variable local
also references an earlier while statement.
However, when I do type "yes" (or "no" for that matter) into the console I receive the invalid input message. I know that the variable again
is a string, as is the "yes" that I'm implying it should be equal to, so I'm quite confused as to why the first if statement is not executing as it should. This is likely something very simple, but this is my first time ever programming in Java, so I apologize if I missed something really obvious!!
Any help would be greatly appreciated.