This question already has an answer here:
- How do I compare strings in Java? 23 answers
I have a Scanner variable and an if else statement to check the line entered by the user. This is at the beginning of my java program. For some reason, when I run this code and enter "michael" the else statement executes instead of the if statement. Everything else is working fine, so why is the condition in the if statement executing false?
I've tried just entering "true" or "2+2==4" in the if statement and then it executes normally, so everything's running fine. I just don't understand why this particular statement is false.
Scanner scan = new Scanner(System.in);
System.out.println("Who is using this, Michael or other? Enter answer
here: ");
String answer = scan.nextLine();
if (answer == "michael" || answer=="Michael") {
System.out.println("result1");
} else {
System.out.println("result2");
}
It seems like it should output result1, but it outputs result2 every time. I always type either "michael" or "Michael"
Aucun commentaire:
Enregistrer un commentaire