-3

(Sorry for the weird title, but I can't figure out what actually the problem is)

The following code should get a String from the command line first (which works), then the input is being splitted (works perfectly, too; I checked by printing both Strings before the if/else as you can see in the part I commented out again) and then it should check what the first part of the splitted String is. And for example if it equals "tweet" it should procedure with the Tweet method.

But somehow it doesn't get that right. It always executes the else statement...

Scanner sc = new Scanner(System.in);
System.out.print("> ");
String input = sc.nextLine();

String[] splitString = input.split(" ");
if(splitString.length != 2){ throw new IllegalArgumentException(); }
String command = splitString[0];
String value = splitString[1];

/*System.out.print(command);
System.out.print(value);*/
if(command == "tweet") { Tweet(value); }
else if(command == "help") { ShowHelp(); }
else { System.out.println("Command "+command+" not found."); }

I tried entering "tweet asdf", but it returns

> tweet asdf
Command tweet not found.

What did I do wrong? I'm confused D:

bertcc423
  • 203
  • 1
  • 4
  • 6

2 Answers2

1

Use the .equals method instead of ==.

== compares the references. .equals will compare the actual content of the two strings.

When comparing strings, you will almost always want to use .equals not == as usually you are wanting to compare content, not reference.

William Morrison
  • 10,953
  • 2
  • 31
  • 48
1

You're using == to compare two objects. This compares their references. Use if(command.equals("tweet")) instead to compare by values.

Due to string interning depending on the JVM and implementation(official classpath, GNU classpath, etc) your approach may operate properly hit-or-miss.

nanofarad
  • 40,330
  • 4
  • 86
  • 117