2013-07-09 84 views
-3

(對不起,我奇怪的冠軍,但我不能找出真正的問題是什麼)獲取字符串→分割→字符串的if/else if語句返回else語句沒有理由

下面的代碼應該首先從命令行獲得一個字符串(工作方式),然後輸入被分割(完美地工作;我通過在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."); } 

我試圖進入 「鳴叫ASDF」,但它返回

> tweet asdf 
Command tweet not found. 

我做了什麼錯?我很困惑D:

回答

1

使用.equals方法而不是==。

==比較參考。 .equals將比較兩個字符串的實際內容。

比較字符串時,您幾乎總是希望使用.equals而不是==,因爲通常您想比較內容而不是參考。

+0

它的工作原理!謝謝!! :D – bertcc423

+0

沒問題。如果這有幫助,請接受答案。 –

1

您正在使用==來比較兩個對象。這比較他們的參考。改用if(command.equals("tweet"))來按值進行比較。

由於字符串實習取決於JVM和實現(官方類路徑,GNU類路徑等),因此您的方法可能正常運行。