我目前有一个游戏,用户需要正确输入密码才能玩游戏。但是,每次我输入“游戏”作为用户代码时,它都会打印出“再见!”,而不是玩游戏。有人可以解释为什么吗?
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!");
}
}
答案 0 :(得分:2)
您应始终将字符串与equals方法进行比较:
if(userCode.equals(gameCode){
...
}
否则,它将比较两个字符串的引用,它们是不同的。但是使用equals()
可以比较字符串的内容。
答案 1 :(得分:0)
您应该使用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!");
}