从命令行获取字符串→拆分字符串→if / else if语句无理由返回else语句

时间:2013-07-09 15:55:34

标签: java string if-statement

(抱歉这个奇怪的标题,但我无法弄清楚究竟是什么问题)

以下代码应首先从命令行获取一个String(有效),然后输入被分割(也完美地工作;我通过在if / else之前打印两个字符串进行检查,如您在部件中看到的那样我再次注释掉)然后它应该检查分割字符串的第一部分是什么。例如,如果它等于“tweet”,它应该使用Tweet方法进行处理。

但不知怎的,它没有那么正确。它总是执行else语句......

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."); }

我尝试输入“tweet asdf”,但它返回

> tweet asdf
Command tweet not found.

我做错了什么?我很困惑D:

2 个答案:

答案 0 :(得分:1)

使用.equals方法代替==。

==比较参考文献。 .equals将比较两个字符串的实际内容。

比较字符串时,您几乎总是希望使用.equals而不是==,因为您通常希望比较内容,而不是引用。

答案 1 :(得分:1)

您正在使用==来比较两个对象。这比较了他们的参考。请使用if(command.equals("tweet"))来比较值。

由于字符串实习取决于JVM和实现(官方类路径,GNU类路径等),您的方法可能会正常运行。

相关问题