我的“输入密码”方法打印出错误的输出

帕特里克·雷内

我目前有一个游戏,用户需要正确输入密码才能玩游戏。但是,每次我输入“game”作为用户代码时,它都会打印出 Goodbye!,而不是玩游戏。有人可以解释为什么吗?

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

}
松饼道

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

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

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章