我试图让一个方法返回短语中n个字母长的单词数。我一直得到字符串索引超出范围:-1错误
public static int nCount(String phrase, int n){
String phrase3 = phrase;
int phrase3Length = phrase3.length();
int counter = 0;
int currentWordLength = 0;
int i = 0; //words checked
int numberOfWords = words(phrase); //already have a method that checks for # of words
while (numberOfWords > i) {
while (phrase3.indexOf(" ") != 0) {
phrase3 = phrase3.substring(1); //line of trouble!! (index out of range -1)
currentWordLength++;
}
while (phrase3.indexOf(" ") == 0) {
phrase3 = phrase3.substring(1);
}
if (currentWordLength == n) {
counter++;
i++;
currentWordLength = 0;
} else {
i++;
currentWordLength = 0;
}
}