【问题标题】:My "Enter the secret code" method is printing out the wrong output [duplicate]我的“输入密码”方法打印出错误的输出[重复]
【发布时间】:2018-12-11 15:55:14
【问题描述】:

我目前有一个游戏,用户需要正确输入密码才能玩游戏。但是,每次我输入“游戏”作为用户代码时,它都会打印出再见!,而不是玩游戏。谁能解释一下原因?

   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!");
    }

}

【问题讨论】:

  • 尝试在 if 语句中使用 userCode.equals(gameCode) 和 !(userCode.equals(gameCode))

标签: java string if-statement java.util.scanner


【解决方案1】:

您应该始终将您的字符串与 equals 方法进行比较:

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

否则它将比较两个字符串的引用,它们是不同的。但是对于equals(),它会比较字符串的内容。

【讨论】:

    【解决方案2】:

    您应该使用equals() 来比较字符串等对象。那么你有:

        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!");
        }
    

    【讨论】:

      猜你喜欢
      • 2018-02-02
      • 2012-05-11
      • 1970-01-01
      • 2015-02-13
      • 2014-12-06
      • 2019-07-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多