StringIndexOutOfBoundsException- Crossword Solver App.
I'm working on a crossword solver that takes user input e.g. h**s*. A text file (dictionary.txt) which contains a list of about 250,000 words is read and matching words are returned i.e. horse, house, etc.
The program kind of works sometimes but mostly i keep getting a StringIndexOutOfBoundsException. I need help. Here is the code so far:
Code:
import java.util.ArrayList;
import java.util.Collection;
public class MatchingWithWildcards {
public static Collection<String> getMatches(String t, String p) {
Collection<String> result = new ArrayList<String>();
for (int i = 0; i < t.length(); i++) {
int j = 0;
int h = i;
int n = p.length();
while(true){
int L = SimpleLongestCommonExtension.longestCommonExtension(p, j, t, h);
if (j + 1 + L == n + 1) {
result.add(t.substring(i, i + n));
break;
}
if (((j + L) < p.length() && p.charAt(j + L) == '*')
|| ((h + L) < t.length() && t.charAt(h + L) == '*')) {
j = j + L + 1;
h = h + L + 1;
} else
break;
}
}
return result;
}
}
Code:
public class SimpleLongestCommonExtension {
public static int longestCommonExtension(String t1, int i1, String t2, int i2) {
int res = 0;
for (int i = i1; i < t1.length() && i2 < t2.length(); i++, i2++) {
if (t1.charAt(i) == t2.charAt(i2))
res++;
else
return res;
}
return res;
}
}
Code:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Collection;
public class Test {
public static void main(String[] args) {
try {
BufferedReader in = new BufferedReader(new FileReader("dictionary.txt"));
String str;
String input = "aa******";
while ((str = in.readLine()) != null) {
if(str.length() == input.length()){
MatchingWithWildcards wild = new MatchingWithWildcards();
Collection<String> results = wild.getMatches(str, input);
if(!results.isEmpty()){
System.out.println(results);
}
}
}
in.close();
}
catch (IOException e) {
System.out.println(e.toString());
}
}
}
OUTPUT:
[aardvark]
[aardwolf]
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 9
at java.lang.String.substring(String.java:1934)
at gmit.MatchingWithWildcards.getMatches(MatchingWith Wildcards.java:20)
at gmit.Test.main(Test.java:23)
[SOLVED] StringIndexOutOfBoundsException- Crossword Solver App.
It's fixed. I changed the line
for (int i = 0; i <= t.length(); i++)
to
for (int i = 0; i <= t.length() - p.length(); i++)