Вопрос

I want to split a string into multiple parts based on parentheses. So if I have the following string:

In fair (*NAME OF A CITY), where we lay our (*NOUN),

The string should be split as:

In fair

*NAME OF A CITY

, where we lay our

*NOUN

I set up a delimiter like so:

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

Because the strings in all caps with an * at the beginning are going to be replaced with user input, I set up a loop like so:

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());
         }

Looks like I'm getting an error with this if statement:

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

When I run it, I get a StringIndexOutOfBoundsException: String index out of range: 0. Not sure why that's happening. Any advice? Thank you!

Это было полезно?

Решение

apparently line = input.nextLine(); gives you a blank string, as @Marco already mentioned.

handle empty line(s) before processing further.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top