我的"Enter the secret code"方法是打印出错误的输出



我目前有一款游戏,用户需要正确输入密码才能玩游戏。然而,每次我输入"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!");
}
}

您应该始终将Strings与equals方法进行比较:

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

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

您应该使用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!");
}

最新更新