0

I currently have a game where the user needs to type in the secret code correctly to play the game. However, each time I type in "game" as the user code, it prints out Goodbye!, rather than play the game. Can someone explain why?

   public static void secretCode() {
      System.out.println("Enter your secret code to play: ");
      Scanner passwordInput = new Scanner(System.in);
      String userCode = passwordInput.nextLine();
      String gameCode = "game";

    if (userCode == gameCode) {
        System.out.println("Let's begin! Each game costs $50 to play.");
        playGame();
        System.out.println("Thanks for playing. Goodbye!");
    }
    if (userCode != gameCode) {
        System.out.println("Goodbye!");
    }

}

2 Answers2

2

You should always compare your Strings with the equals method:

if(userCode.equals(gameCode){
    ...
}

Otherwise it will compare the references of the two Strings and they are different. But with equals() it compares the content of the strings.

MuffinMICHI
  • 480
  • 5
  • 13
0

you should use equals() to comparate Objects like Strings. Then you have:

    System.out.println("Enter your secret code to play: ");
    Scanner passwordInput = new Scanner(System.in);
    String userCode = passwordInput.nextLine();
    String gameCode = "game";
    // compare with equals
    if (userCode.equals(gameCode)) {
        System.out.println("Let's begin! Each game costs $50 to play.");
        playGame();
        System.out.println("Thanks for playing. Goodbye!");
    }
    // compare with eaquals
    if (!userCode.equals(gameCode)) {
        System.out.println("Goodbye!");
    }
elbraulio
  • 994
  • 6
  • 15