+ 1

What am I doing wrong with this if-statement?

After asking a question, somebody has to reply with yes or no. I want to give an proper answer to their yes or no by using an if-statement. But it doensn't matter what I do - Java replies every time with the "else statement". The "if statement" never seems to be true. Scanner scan = new Scanner (System.in); ... //asking question String answer = scan.nextLine(); if (answer == "yes" || answer == "Yes") { System.out.println("That is great!"); } else { System.out.println("Maybe next time?"); }

24th Apr 2018, 11:14 AM
Steffanie
Steffanie - avatar
5 Antworten
+ 2
You have to take cure about strings equality... == check equality for object reference (on objects) not on values because of this java String (not only it) has "equals" method for check string value equality
24th Apr 2018, 11:27 AM
KrOW
KrOW - avatar
+ 1
I wish I could post a photo here, because I still get the answer "Maybe next time?" after I replied yes to the question...
24th Apr 2018, 11:20 AM
Steffanie
Steffanie - avatar
+ 1
Thanks a lot! I forgot I can't use = when I compare strings... It has to be answer.equels indeed.
24th Apr 2018, 11:26 AM
Steffanie
Steffanie - avatar