簡體   English   中英

分割字符串Java空間

[英]Split String Java Space

如果有人可以幫助我,那將是非常棒的。

我正在嘗試使用Java的Split命令,使用空格分隔字符串,但問題是,字符串可能沒有空格,這意味着它只是一個簡單的順序(而不是“輸入2 “將是“退出”)

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

當我嘗試此操作時,如果我輸入“ enter 3”(因為“ first = enter”和“ second = 3”)會起作用,但是如果我輸入“ exit”,則會拋出錯誤,因為second沒有值。 我想拆分字符串,所以當我嘗試以下操作時:

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

有人可以幫忙嗎? 謝謝!

在確定存在第二個元素之前,請不要嘗試訪問它。 例:

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.length試圖訪問的元素之前comando2 您應該做同樣的事情。

這個怎么樣?

...
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 a ? b : c的計算結果為b ,如果a是真或c如果a是假的。 這個? : ? :運算符稱為三元運算符。

為什么不檢查它是否有空格,如果有,則以不同的方式處理它:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM