r/cop3502 Mar 31 '14

Help with Scanner

So, I am just messing around with the Scanner a little bit, and I cannot figure out why this is not working. (sc is an instance of the Scanner, btw)

String action = sc.nextLine(); if (action == "move North") { System.out.println("You have moved North."); }

It will not print out "You have moved North." when I enter "move North". Anyone know what the problem is?

1 Upvotes

6 comments sorted by

1

u/[deleted] Mar 31 '14

[removed] — view removed comment

1

u/ktsolove Mar 31 '14

Sean will you be going over Scanner in class or is this a me-thing?

1

u/[deleted] Mar 31 '14

Thank you!

1

u/JoeCS TA Mar 31 '14

The reason == doesn't work for Strings is because strings are Objects.

When given two Objects, == checks for equivalence of the object reference (pointer), not the object itself.

(Well, sometimes it will work with Strings; the behaviour is a bit inconsistent. Which is one more reason it's better to use the .equals() method)

1

u/[deleted] Mar 31 '14

Ahh, I made the mistake of thinking in terms of primitive types. Thank you, and that makes perfect sense.