2015-01-15 117 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是假的。这个? :运算符被称为三元运算符。