StringIndexOutOfBoundException in Java

How to avoid StringIndexOutOfBoundException in this code ? I want to get every two characters in the string.

String path = input.nextLine();

    for(int i = 0; i < path.length(); i++ )
    {
        String n = path.substring(i,i+1);
        String nPlus1 = path.substring(i+1, i+2);
    }
Jon Skeet
people
quotationmark

On the last iteration, i will be equal to path.length() - 1. Therefore in this statement:

String nPlus1 = path.substring(i+1, i+2);

... the first argument will be equal to path.length(), and the second argument will be equal to path.length() + 1. The first argument is valid; the second isn't. As per the Javadoc:

IndexOutOfBoundsException - if the beginIndex is negative, or endIndex is larger than the length of this String object, or beginIndex is larger than endIndex.

To fix this, just adjust your loop bounds:

for(int i = 0; i < path.length() - 1; i++)

(It's not really clear what you mean by "I want to get every two characters in the string" but this will at least not throw an exception.)

people

See more on this question at Stackoverflow