Jon Brown Jon Brown - 4 years ago 123
Java Question

StringIndexOutOfBoundsException : Problems with String.substring() and String.indexOf()

I'm writing a program that reverses the word order in a sentence. (e.g. "the red hat belongs to John" => "John to belongs hat red the") I walked myself through the do-while loop, but I don't understand why there is an Index Exception.

Thanks for your help,

JonBrown




Exception :

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -23
at java.lang.String.substring(Unknown Source)
at WordReverse.main(WordReverse.java:17)


Code :

public class WordReverse
{
public static void main(String[] args)
{
String input = "The red had belongs to John";
String reverse = "";
int lastSpace = 0;

do
{
//Isolate Word w/ Preceding Space
int startIndex = lastSpace;
int endIndex = input.indexOf(' ', startIndex + 1);

//Add Word to front of String
reverse = input.substring(startIndex, endIndex) + reverse;

//Add Preceding Space for First Iteration
if (lastSpace == 0) reverse = " " + reverse;

//Reset Last Space
lastSpace = endIndex;

// Repeat Loop Until line14 .indexOf returns -1 due to lack of " ".
}while (lastSpace != -1);

System.out.println(reverse);
}
}

Answer Source

As others have noted, your problem is with lastIndex being -1 . This fix breaks out of the loop when that happens, but not before copying the remainder of the string to the result:

public class WordReverse 
{
    public static void main(String[] args)
    {
        String input = "The red hat belongs to John";
        String reverse = "";
        int lastSpace = 0;

        do
        {
            //Isolate Word w/ Preceding Space
            int startIndex = lastSpace;
            int endIndex = input.indexOf(' ', startIndex+1);
            if (endIndex==-1) {
                reverse = input.substring(startIndex) + reverse;
                break;
            }

            //Add Word to front of String 
            reverse = input.substring(startIndex, endIndex) + reverse;

            //Add Preceding Space for First Iteration
            if (lastSpace == 0) reverse = " " + reverse;

            //Reset Last Space
            lastSpace = endIndex;

            // Repeat Loop Until line14 .indexOf returns -1 due to lack of " ". 
        }while (true);

        System.out.println(reverse);
    }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download