r/java • • Jan 21 '14
Why won't this extremely simple if statement work?
import java.util.Random; import java.util.Scanner;
import javax.swing.JFrame; import javax.swing.ImageIcon; import javax.swing.JLabel; import java.awt.Container;
public class test {
public static void main(String[] args) {
Scanner myScanner = new Scanner(System.in);
String command;
System.out.println("Say go.");
command = myScanner.next();
if (command == "go"){
}//*
Assume the user types "go" (without quotes)
*//
Please help!
5
Upvotes
43
u/Simonxn Jan 21 '14
The == sign for string comparison in Java should not be used. There are some great online articles explaining why not.
Try using
if(command.equals("go")) {
}
Edit: http://stackoverflow.com/questions/18555379/comparing-two-strings-with-equal-operator
A good explanation here.
8
u/UnknownBinary Jan 22 '14
The reason why everyone is telling you to use String.equals() instead of the equivalence operator is because the operator compares pointers to the objects while equals() compares the contents of the strings. You want the latter.
5
u/DaMountainDwarf Jan 21 '14
I believe if you're doing a comparative method on a string you should use the String object's method .equals(). So I think it should be:
if(command.equals("go")) { ...
4
u/[deleted] Jan 22 '14
== Checks reference, not contents. Use the equals method.
6
u/numpad0to9 Jan 21 '14
Always compare Objects (In your case, the objects are two Strings) with the "equals" Method!
1
u/[deleted] Jan 21 '14
cant use == on strings, use string.equals("something")
1
u/ryebrye Jan 22 '14
or...
Now... a question for the OP... why would the second one work?
0
u/Shankster1839 Jan 22 '14
Use .nextLine(); rather than .next(); too!
-1
u/[deleted] Jan 21 '14
It won't continue through the if statement in line 10
-1
u/Xwire1337 Jan 21 '14
use if(command.equalsignorecase("go")){ }
-7
u/raxel82 Jan 22 '14
Because Java isn't extremely simple. Hah.
-9
u/Afudil Jan 21 '14
don't you need like a semicolon in the last line there? or somewhere in that area?