【问题标题】:StringIndexOutOfBoundsException when using delimiter使用分隔符时出现 StringIndexOutOfBoundsException
【发布时间】:2014-05-11 16:39:53
【问题描述】:

我想根据括号将字符串拆分为多个部分。所以如果我有以下字符串:

公平地说 (*NAME OF A CITY),我们的 (*NOUN),

字符串应该被拆分为:

公平

*城市名称

,我们放置的地方

*名词

我这样设置分隔符:

String delim = "[()]";
String [] inputWords = line.split (delim);

因为开头带 * 的所有大写字符串都将被用户输入替换,所以我设置了一个这样的循环:

while (input.hasNextLine())
      {
         line = input.nextLine();
         String [] inputWords = line.split (delim);

            for (int i = 0; i < inputWords.length; i++)
            {
               if (inputWords[i].charAt(0) != '*')
               {
                  newLine.append (inputWords[i]);
               }

               else
               {
                  String userWord = JOptionPane.showInputDialog (null, inputWords[i].substring (1, inputWords[i].length()));
                  newLine.append (userWord);
               }              
            }

            output.println (newLine.toString());
            output.flush();
            newLine.delete (0, line.length());
         }

看起来我在使用这个 if 语句时遇到了错误:

if (inputWords[i].charAt(0) != '*')

当我运行它时,我得到一个 StringIndexOutOfBoundsException: String index out of range: 0。不知道为什么会这样。有什么建议吗?谢谢!

【问题讨论】:

  • 啊,你是对的,谢谢!

标签: java string delimiter indexoutofboundsexception


【解决方案1】:

显然line = input.nextLine(); 给你一个空白字符串,正如@Marco 已经提到的。

在进一步处理之前处理空行。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-24
    • 2020-08-11
    • 2017-09-06
    • 1970-01-01
    相关资源
    最近更新 更多