0

public class User implements GameObject{

private Scanner userScanner;
private int result = 0;

public User() {
    userScanner = new Scanner(System.in);
}

public int getGameObject() {
    System.out.println("Rock: 1, Paper: 2 or Scissors: 3");
    String userInput = userScanner.nextLine();

    if (userInput == "1" || userInput == "2" || userInput == "3") {
        // User has entered a valid input
        switch (userInput) {
            case "1":
                return 1;
            case "2":
                return 2;
            case "3":
                return 3;
        }
    }
    return getGameObject();
}

}

My problem is the result from getGameObject() method. When I am using this in the application its always return 0 or a value I set in the last return (int fex 2). I want to get user values (0,1,2). My plan is to return at the end method itself to get back to the first propmpt line in case wrong selection from the user. In such case method always return method recall and I fall in kind of infinite loop. Could you help?

  • Don't compare Strings using `==` or `!=`. Use the `equals(...)` or the `equalsIgnoreCase(...)` method instead. Understand that `==` checks if the two *object references* are the same which is not what you're interested in. The methods on the other hand check if the two Strings have the same characters in the same order, and that's what matters here. – Hovercraft Full Of Eels Dec 27 '17 at 15:32
  • 1
    The `if` condition is both wrong and completely unnecessary, since the `switch` statement will compare the strings correctly. – khelwood Dec 27 '17 at 15:33
  • thank you, it works ok now. SUre I forget that I should not use == in this case. – Dariusz Mozgowoj Dec 27 '17 at 16:16

0 Answers0