如果有人能帮助我,那就太好了。
我正在尝试使用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”,它会抛出一个错误,因为第二个没有值。 我想分割字符串,所以当我尝试执行以下操作时:
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
的元素之前,此代码始终会检查 comando2.length
。你也应该这样做。
关于java - 分割字符串 Java 空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27955146/