拆分字符串java空间

noj0wjuj  于 2021-06-30  发布在  Java
关注(0)|答案(3)|浏览(302)

如果有人能帮我,那就太棒了。
我正在尝试使用java的split命令,使用空格分割字符串,但问题是,可能字符串没有空格,这意味着它将只是一个简单的顺序(不是“enter 2”,而是“exit”)

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

当我尝试这个方法时,如果我写“enter3”就行了,因为“first=enter”和“second=3”,但是如果我写“exit”,它会抛出一个错误,因为second没有值。我想拆分字符串,因此当我尝试执行此操作时,请执行以下操作:

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

有人能帮忙吗?谢谢您!

wfauudbj

wfauudbj1#

为什么不检查它是否有空格,如果有,则进行不同的处理:

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

wlp8pajw2#

在确定数组中的第二个元素存在之前,不要尝试访问它。例子:

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 . 你也应该这么做。

fhg3lkii

fhg3lkii3#

这个怎么样?

...
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 是假的。这个 ? : 算子称为三元算子。

相关问题