why does this give a StringIndexOutOfBoundsException?

41 views Asked by At

This code is part of a method to add a word to a radix tree. if I call this method with the word in the parameter [e.g. addWord("food", node)], it throws a StringIndexOutOfBoundsException at the char character = word.charAt(0); line. I am struggling to figure out why that is. I have tried changing the number and still gets the same result.

    private void addWord(String word, RadixNode node) 
    {
        RadixNode childNode;
        word = word.toLowerCase();
        do
        {
            char character = word.charAt(0);
1

There are 1 answers

5
NoDataFound On

The most likely reason is because your String word is empty.

You should check for emptiness before:

private void addWord(String word, RadixNode node) {
  if (word.isEmpty()) {
    // do nothing
    return;
  }
  ...
}

You could also throw an explicit exception (eg: IllegalArgumentException) or handle this case.

If word should not be empty, then that's mean you have to check method calling addWord.