2015-01-15 115 views
0

如果有人可以幫助我,那將會很棒。拆分字符串Java空間

我想使用Java的拆分命令,使用空間拆分字符串,但問題是,也許字符串不會有空間,這意味着它將只是一個簡單的順序(而不是的「輸入2」這將是「退出」)

Scanner SC = new Scanner(System.in); 
String comando = SC.nextLine(); 
String[] comando2 = comando.split("\\s+"); 
String first = comando2[0]; 
String second = comando2[1]; 

當我嘗試這一點,它的工作原理,如果我寫「進入3」,因爲「第一=輸入」和「第二= 3」,但如果我寫的「退出」它會拋出一個錯誤,因爲第二個沒有值。 我想分裂字符串,所以當我嘗試這下面:

if (comando.equalsIgnoreCase("exit")) 
    // something here 
else if (first.equalsIgnoreCase("enter")) 
    // and use String "second" 

有人能幫忙嗎?謝謝!

+0

你的問題是什麼?你的代碼應該工作,除非你正在做錯誤的評論('/ /而不是'/')。 –

+0

不,在Java中,您無法使用尚未初始化的值。這就是爲什麼我的代碼不起作用。 – carlos

+0

我的意思是第二個例子(用'if'子句),它做了一些隱式檢查。 –

回答

4

不要嘗試訪問數組中的第二個元素,直到確定它存在。例如:

if(comando2.length < 1) { 
    // the user typed only spaces 
} else { 
    String first = comando2[0]; 
    if(first.equalsIgnoreCase("exit")) { // or comando.equalsIgnoreCase("exit"), depending on whether the user is allowed to type things after "exit" 
     // something here 

    } else if(first.equalsIgnoreCase("enter")) { 
     if(comando2.length < 2) { 
      // they typed "enter" by itself; what do you want to do? 
      // (probably print an error message) 
     } else { 
      String second = comando2[1]; 
      // do something here 
     } 
    } 
} 

聲明本代碼總是如何試圖訪問的comando2元素之前檢查comando2.length。你應該這樣做。

+0

謝謝!你幫了我很多工作 – carlos

-1

爲什麼不檢查是否有空格,如果確實如此不同的處理:

if (comando.contains(" ")) 
{ 
    String[] comando2 = comando.split(" "); 
    String first = comando2[0]; 
    String second = comando2[1]; 
} 
else 
{ 
    String first = comando; 
} 
+0

這是不好的設計。你永遠無法假定一個單詞總會在空格後面出現。如果用戶輸入一個空格後面的字符串,這將失敗。 – NullEverything

1

這個怎麼樣?

... 
String[] comando2 = comando.split("\\s+"); 
String first = comando2.length > 0 ? comando2[0] : null; 
String second = comando2.length > 1 ? comando2[1] : null; 
... 

你的問題是,你在訪問一個數組元素之前,你知道它是否存在。這樣,如果數組足夠長,則獲得該值,否則返回null。

表達a ? b : c計算結果爲b如果a爲真或c如果a是假的。這個? :運算符被稱爲三元運算符。