简体   繁体   中英

why does this give a StringIndexOutOfBoundsException?

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 [eg 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);

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM