Michele Rosito Michele Rosito - 5 months ago 11
Java Question

StringIndexOutOfBoundsException: string index out of range

I can't find an answer about this exception. THe program is very simple but, i don't know why is incorrect.

/**
* Program selects the first word from the sentence "Hello, my dear!" with
* the String Classes's methods this.indexOf() and this.substring()
*
*
* Last modify: 29th October 2015
*/

public class TakeSubstringWanted {

public static void main(String[] args) {

String sentence = "Hello, my dear!";
String reference = "Hello";

System.out.println("The sentence is: " + sentence);
System.out.println("You want to take the first word of that sentence");
System.out.println("Give me a second...");

int firstReference = sentence.indexOf(reference);
int firstLength = reference.length();
System.out.println("The first reference of the searched word is " + firstReference);
System.out.println("The first word of the sentence " + sentence + " is: " + "\"" + sentence.substring(firstReference, firstLength) + "\"");
int secondReference = sentence.indexOf("my");
System.out.println("The second reference of the searched word is " + secondReference);
int secondLength = "my".length();
System.out.println(secondLength);
System.out.println(sentence);
System.out.println("The second word of the sentence " + sentence + " is: " + "\"" + sentence.substring(secondReference, secondLength) + "\"");
}

}

Answer

Your Problem is here:

sentence.substring(secondReference, secondLength)

Your giving to lengths but it should be

sentence.substring(startIndex, endIndex);

Hope that helps!

Comments