-4
我有一個簡單的java代碼總是返回"Game over."
。Java如果其他工作不正常
import java.util.Scanner;
public class nextQuestion {
public void newQuestion() {
Scanner choice2 = new Scanner(System.in);
System.out.println("What is my name?");
System.out.println("A. Mark");
System.out.println("B. Robert");
System.out.println("C. Mio");
System.out.println("D. Samantha");
String answer2 = choice2.nextLine();
if(answer2 == "a" || answer2 == "A") {
System.out.println("Game over.");
System.exit(0);
} else if(answer2 == "b" || answer2 == "B") {
System.out.println("Nice guess!");
System.exit(0);
} else if(answer2 == "c" || answer2 == "C") {
System.out.println("Game over.");
System.exit(0);
} else if(answer2 == "d" || answer2 == "D") {
System.out.println("Game over.");
System.exit(0);
} else {
System.out.println("Game over.");
System.exit(0);
}
}
}
但是,如果我使用switch語句,它確實有效。這有什麼問題?
Java的if/else工作;只是你做錯了事。 – fge
您錯誤地比較了字符串。你應該使用String類的equals()方法。 – Sudheer