Mike Mike - 2 years ago 112
Java Question

index out of range when trying to use substring

I made a simple program to spell-check words. The program has 2 inputs, an array of String that works as a dictionary and a String that is a sentence. The program checks the sentence (word to word) and checks the dictionary to find a simmilar word, then it asks the user if they meant to write the word in the dictionary.

Requirements:
The first 2 characters need to be the same.
The word in the dictionary can only have 2 more characters than the sentence word.
The word in the dictionary can only have 2 different characters than the word in the sentence. (The only characters that count are the ones with index between 0 and the length of the sentence word. E.g. efg and egg|s)

public static String SpellCheck(String[] dictionary, String sentence){
Scanner sc = new Scanner(System.in);
String newSentence = "";
StringTokenizer divisor = new StringTokenizer(sentence);
while(divisor.hasMoreElements()){
String word = divisor.nextToken();
String a = "";
for(int i = 0; i<dictionary.length; ++i){
int n = 0;
if(word.length()>2 && dictionary[i].length()-word.length()<=2 && word.substring(0,2).indexOf(dictionary[i].substring(0,2))==0){
String s1 = word.substring(2,word.length());
String s2 = dictionary[i].substring(2,dictionary[i].length());
for(int k = 0; k<s1.length(); ++k){
String l1 = s1.substring(k,k+1);
String l2 = s2.substring(k,k+1);
if(l1.indexOf(l2)!=0)++n;
}
if(n<=2){
System.out.print(dictionary[i] + "?");
a = sc.nextLine();
if("yes".indexOf(a)==0){
newSentence += dictionary[i] + " ";
break;
}
}
}
}
if("yes".indexOf(a)!=0)newSentence += word + " ";
}
return newSentence;
}


The problem is at the line

String s2 = dictionary[i].substring(2,dictionary[i].length());


It works for the first word in the sentence but in the second time I get an error saying "String index is out of range" and I can't figure out why since I'm using .length() to find the index of the last letter. I hope someone can help me figuring out what's wrong with this program. Thank you!

Answer Source

I believe your error is in the for loop just below where you've said the error is

String s2 = dictionary[i].substring(2,dictionary[i].length());

for(int k = 0; k<s1.length(); ++k){ //HERE
    String l1 = s1.substring(k,k+1);
    String l2 = s2.substring(k,k+1);
}

When setting l1 and l2, you will be exceeding the bounds of your string index. the for loop should read

for(int k = 0; k < s1.length()-1; ++k){
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download