I just read through seven threads related to Java Scanner issues, but none contained the answer to my problem.
I'm trying to get user input form the console. I create a Scanner object (input) then try to store the user's command in a string called "command." Then I pass "command" back to the original runGame function. It seems that Scanner/command do read the write text. (If I enter 'd' and then print command's contents it prints 'd'.)
But when I return the string and store it in nextMove, it breaks. For example, I'll enter 'd' but then (nextMove == 'd') if statement isn't called. In fact, no matter what I enter, only the else statement is entered.
What am I doing wrong? How can I fix it
Here's the original function code:
public void runGame() {
drawWindow();
while(true) {
String nextMove = takeInput();
if(nextMove == "d")
System.out.print("WORRRRDDD d");
else if(nextMove == "w")
System.out.print("WORRRRDDD w ");
else {
drawWindow();
System.out.print("YOU GOT ELSED");
continue;
}
}
}
And here's the takeInput/Scanner function code:
public String takeInput() {
String command;
input = new Scanner(System.in); // "input" is the Scanner object used for all input.
try{
System.out.print("Enter command (d, w, stop, restart, exit): ");
command = input.next();
} catch(Exception e) {
System.out.println("You entered an invalid command.");
return null;
}
System.out.println("\n RETURNING COMMAND" + command + " \n");
return command;
}
While you're helping (I'm going to search but if I don't find it) what's the best way to recognize blank input in a scanner object?
And should are there any other exceptions/catches I need to worry about for user input in a console?