1

以下代码的 lang.StringIndexOutOfBoundsException。该程序检查没有空格的句子以提取与有效英语单词词典匹配的单词

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

class WordCheckUtil{

boolean dictionaryContains(String word)
{
    List<String> dictionary = new ArrayList<String>(Arrays.asList("mobile","samsung","sam","sung",
                            "man","mango", "icecream","and",
                            "go","i","love","ice","cream"));

        if(dictionary.contains(word))
            return true;

    return false;
}

void wordCheck(String str){
    wordBreakCheck(str,str.length(),"");
}

void wordBreakCheck(String str, int length, String result){
    System.out.println(str+" "+length+" "+result);
    for (int i = 1; i <= length; i++) {
        String prefix = str.substring(0, i);
        System.out.println(prefix);
        if(dictionaryContains(prefix)){

            if(i == length){
                result += prefix;
                System.out.println("--> "+result);
                return;
            }
            System.out.println(i+" -- "+length);
            String subStr = str.substring(i,length-i);
            wordBreakCheck(subStr,length-i,result+prefix+" ");
        }
    }
}

public static void main(String[] args) {
    WordCheckUtil wr = new WordCheckUtil();
    wr.wordCheck("iloveice");
}

}

这是我得到的错误堆栈:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String 
index out of range: -1
    at java.lang.String.substring(String.java:1967)
    at WordCheckUtil.wordBreakCheck(WrodCheckUtil.java:36)
    at WordCheckUtil.wordBreakCheck(WrodCheckUtil.java:37)
    at WordCheckUtil.wordCheck(WrodCheckUtil.java:20)
    at WordCheckUtil.main(WrodCheckUtil.java:44)
4

2 回答 2

3

子字符串接受开始和结束索引,而不是长度。该行:

str.substring(i,length-i); 

要求从索引i(4) 到index length-i(3) 的字符串,而不是剩余长度的字符串。

取出-i。

于 2017-04-13T19:00:45.997 回答
0

你写了:

str.substring(i,length-i);

i增加,并且在某一时刻i将 >= length - i

于 2017-04-13T18:46:13.277 回答