I am working on a simple spell checker which grabs the alphabet from a text file and then checks any word for whether it is a correct spelling or not using a trie
Code
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;
public class Spellchecker {
static final int ALPHABET_SIZE = 26;
static class node {
node[] children = new node[ALPHABET_SIZE];
boolean isEndOfWord;
node() {
isEndOfWord = false;
for (int i = 0; i < ALPHABET_SIZE; i++)
children[i] = null;
}
}
static node root;
static void insert(String key) {
int length = key.length();
node pCrawl = root;
for (int level = 0; level < length; level++) {
int index = key.charAt(level) - 'a';
if (pCrawl.children[index] == null)
pCrawl.children[index] = new node();
pCrawl = pCrawl.children[index];
}
// mark last node as leaf
pCrawl.isEndOfWord = true;
}
static int wordCount (node root){
int result = 0;
if (root.isEndOfWord){
result++;
}
for (int i = 0; i < ALPHABET_SIZE; i ++){
if (root.children[i]!=null){
result += wordCount(root.children[i]);
}
}
return result;
}
// Returns true if key presents in trie, else false
static boolean search(String key) {
int length = key.length();
node pCrawl = root;
for (int level = 0; level < length; level++) {
int index = key.charAt(level) - 'a';
if (pCrawl.children[index] == null)
return false;
pCrawl = pCrawl.children[index];
}
return (pCrawl != null && pCrawl.isEndOfWord);
}
public static void main(String args[]) throws IOException {
ArrayList<String> dictionary = new ArrayList<>();
ArrayList<String> text = new ArrayList<>();
try (BufferedReader br = new BufferedReader(new FileReader("dictionary.txt"))) {
while (br.ready()) {
dictionary.add(br.readLine());
}
} catch (Exception e) {
e.printStackTrace();
}
root = new node();
int i;
for (i = 0; i < dictionary.size(); i++)
insert(dictionary.get(i));
if (!search(){
System.out.println("not in dictionary: " + text.get(j));
}
}
}
}
the error I get is very confusing
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index -65 out of bounds for length 26
at ASS1.Spellchecker.search(Spellchecker.java:67)
at ASS1.Spellchecker.main(Spellchecker.java:126)
I have absolutely no idea how it could possibly be -65
. any help would be greatly appreciated.
Based on your code and the error, I think your search
key has a space
character in it, so space
character ASCII code is 32
, so while searching
int index = key.charAt(level) - 'a';
//key.charAt(level) = space = 32
//index = 32 - 'a' = 32 - 97 = -65 //invalid index
The best solution for this is, if your input is not all lower case english alphabet, then better use HashMap
for holding children instead of array
.