2017-08-31 55 views
2

我想獲得的平均字長爲一組字符串,我運行到下面的錯誤:平均字長

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; 
} 
+0

哪條線的代碼不會例外從何而來? – 4castle

+4

無法在我的環境中重現。 'tweeps'的價值是什麼? – ymonad

+0

順便說一句,'sum/count'正在做整數除法(所以它會截斷小數點後面的數字)。在執行操作之前,您可能需要'1.0 * sum/count'以便將計算結果提升爲'double'。 – 4castle

回答

2
import java.lang.*; 

class test{ 

    public static void main(String args[]) 
    { 
     String MySentence = "This is My Word. I'm Going to Find the Average of this"; 
     System.out.println(" Average Length :"+ getAverageWordLength(MySentence)); 
    } 

    static double getAverageWordLength(String tweeps) { 

     // 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; 
    } 
} 
+0

你改變了什麼? – Jack

+0

我在下面的getAverageWordLength(MySentence)中將「tweeps」作爲主函數中的參數傳遞。然後,「tweeps」在執行時會有一個值。 –

+0

我有我的tweeps靜態私人字符串在我的課,功能是在課堂上。難道不會和你的一樣嗎?我不確定這是否是問題。 – Jack