我想獲得的平均字長爲一組字符串,我運行到下面的錯誤:平均字長
java.lang.StringIndexOutOfBoundsException:字符串索引超出範圍:-1
我不確定它是由什麼引起的。這裏是我的代碼:
static double getAverageWordLength() {
// TODO: update the code here to return the average length of words in the tweets processed so far.
String[] average = tweeps.split(" ");
int count = 0;
int sum = 0;
int currentWordLength;
String tempString;
for(int i = 0; i < average.length; i++)
{
average[i] = average[i].replaceAll("[^a-zA-Z]", "").toLowerCase();
tempString = average[i];
currentWordLength = tempString.length();
sum += currentWordLength;
count++;
}
double averageWordLength = sum/count;
return averageWordLength;
}
哪條線的代碼不會例外從何而來? – 4castle
無法在我的環境中重現。 'tweeps'的價值是什麼? – ymonad
順便說一句,'sum/count'正在做整數除法(所以它會截斷小數點後面的數字)。在執行操作之前,您可能需要'1.0 * sum/count'以便將計算結果提升爲'double'。 – 4castle