So I'm teaching myself Java. I'm creating a text based game. I have an if statement that i want to check users input so its like this:

if(sc.next() = "help"){
} else if(sc.next() = "item"){

Etc. But it wont work. What would be the proper way to do this? Do i need to capture the users input into a variable first then compare?

2 Years
Discussion Span
Last Post by stultuske

That's an assignment. You need 2 equals. Like this: if(sc.next() == "help").

Edit: Actually, you should probably use String.equals() for this. Not the == operator.

Edited by John Code


Indeed. just to add the reason why it should be euals, since it's very important that you get that straight away:

'==' compares references. you can compare the value of primitive datatypes (int, boolean, ... ) using == without a problem, but when it comes to Objects, you'll want to compare the values, not the references.

for instance:

String a = "one";
String b = "one";
String c = new String("one");

it is clear that all these instances of String have the same value. they do not, however, have the same reference.

boolean d = a == b;
boolean e = a == c;
boolean f = a.equals(c);

here, d is true, e is false (since using the new keyword, you force a new instance, instead of using the value that might already be in the String pool) and f is true. even though they don't have the same reference, they do have the same value.

for the String class, there is a special 'version' of the equals method, btw, being the equalsIgnoreCase, which will compare two Strings, disregarding case related differences (upper vs lower cases)

String a = "one";
String b = "oNe";
boolean c = a.equals(b);
boolean d = a.equalsIgnoreCase(b);

in this example: c will be false, since the Strings don't have the identical same value (because of the 'N') and d will be true, since, if you ignore the case differences, the values of a and b are identical.

Votes + Comments
+1 for showing equalsIgnoreCase() which I didn't even know
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.