-2

Scanner class doesn't work how I expected.

Scanner in = new Scanner(System.in); // input: total

String str = in.nextLine();          // total
System.out.println(str);             // total
System.out.println(str == "total");  // false
System.out.println(str != "total");  // true

I expected line 5 being true, but the above code is what i got.

How should I do for (str == "total") becomes true?

1 Answers1

1

Use .equals() instead of == to compare strings.

Roland Weber
  • 1,865
  • 2
  • 17
  • 27
  • when giving answers, you should always try to add some more clarification. It's nice that the OP now knows to use equals, it would be better that he understood why and in which cases. – Stultuske Feb 07 '19 at 10:02
  • Actually, I was tempted to flag the question for removal. This is a beginner's problem that was bound to have detailed answers elsewhere. I just felt that answering was quicker than searching for the duplicates. Maybe I'll go with a comment next time. – Roland Weber Feb 07 '19 at 14:08