Exception in thread “main” java.lang.StringIndexOutOfBoundsException: String index out of range: -60

StackOverflow https://stackoverflow.com//questions/21012521

Question

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -60

I keep getting this error, and I've been try to figure it out, but I just can't! I'm just starting java so any and all help is much appreciated! Here's my code:

//This method takes large amounts of text and formats
//them nicely in equal lenth lines for the console.

public void print(String a){

    String textLine = a;
    int x = 60; 
    List<String> splitText = new ArrayList<String>();

    //limits the amount of characters in a printed line to 60 + the next word.
    while (textLine.length() > 60) {

        if (textLine.substring(x+1,1) == " "){          
            splitText.add(textLine.substring(0,x+1));
            textLine = textLine.substring(x+2);
            x = 0;
        }           
        else {          
            x++;
        }
    }

    splitText.add(textLine);

    for (int y = 0; splitText.size() < y;y++){

        System.out.println(splitText.get(y));

    }

}
Was it helpful?

Solution

The problem is that you are trying to call substring(beginIndex, endIndex) with the parameters:

beginIndex = x + 1 = 61
endIndex = 1

According to substring docs:

Returns a new string that is a substring of this string. The substring begins at the specified beginIndex and extends to the character at index endIndex - 1. Thus the length of the substring is endIndex-beginIndex.

This will fall in a length of 1 - 61 = -60. That's the reason of the Exception:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -60 ...

Here are some examples (from docs), on how to use this method:

"hamburger".substring(4, 8) returns "urge"
"smiles".substring(1, 5) returns "mile"

Edit:

Another error (thanks to @ichramm) is in the for-loop where you are printing the results. The end condition should be y < splitText.size()

for (int y = 0; y < splitText.size(); y++) {
    ...
}

OTHER TIPS

Due to substring method.

public String substring(int beginIndex)

or

public String substring(int beginIndex, int endIndex)

Parameters : Here is the detail of parameters :

beginIndex -- the begin index, inclusive .

endIndex -- the end index , exclusive.`
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top