以下代码的 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)