2013-03-04 61 views
0

我正在製作一個計算一個句子中的單詞的程序。空格不計算,標點符號不計算。我正在使用一個模塊,它將接受輸入並輸出答案。不過不要擔心,因爲我不認爲這就是爲什麼我的程序打印出這個繼續索引超出範圍

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: 
String index out of range: 11 
    at java.lang.String.charAt(String.java:658) 
    at WordCount.main(WordCount.java:20) 
public class WordCount{ 
    public static void main(String[] args){ 

     System.out.println("Please enter sentence"); 
     String sentence= IO.readString(); 

     System.out.println("Please enter minimum word length"); 
     double minword= IO.readInt(); 

     String word; 
     int wordletter=0; 
     int wordcount= 0; 

     int count= -1; 
     int end= sentence.length(); 

     do{ 
      count++; 
      char space= sentence.charAt(count); 

      if(Character.isLetter(space)){ 
       boolean cut= Character.isSpaceChar(space); 
       if(cut== true) 
        word=sentence.substring(0,count); 
        count= 0; 
        wordletter= word.length(); 
        end= end- wordletter; 

        if(wordletter< minword){ 
         ; 
        }else{ 
         wordcount= wordcount+1; 
        } 
       }else{ 
        ; 
       } 
      }else{ 
       ; 
      } 
     }while(count!= end); 

    IO.outputIntAnswer(wordcount); 

    } 
} 

回答

0

char space= sentence.charAt(count);,因爲你的循環條件運行的次數過多造成的除外。你想比,而不是不小於等於爲while條件

while (count - 1 < end); 

的減1是必需的,因爲你已經構建了您的循環在陌生的路上,我通常會去這樣的事情:

int end= sentence.length(); 
count = -1; 
while (++count < end) { 

} 

或者,甚至更好。使用for循環。

int end = sentence.length(); 
for (int i = 0; i < end; i++ { 
    // ... 
} 
+0

我試過這個,我得到了同樣的錯誤? – mercedesbrenz 2013-03-04 02:59:25

+0

你確定你把它正確地複製了嗎? (刪除了身體的任何數量++)。它應該從0運行到sentence.length() - 1. – 2013-03-04 03:11:46

+0

是的,我做到了。在我使用do while循環之前,我使用了for循環並得到了相同的錯誤。 – mercedesbrenz 2013-03-04 03:26:52

0

簡單的回答是,一個陣列具有array.length元件,其索引是0, 1, ... array.length - 1。你的代碼(正如書面)將嘗試索引0, 1, ... array.length

想想你正在使用的終止循環的條件。


但這並不足以解決您的計劃。我至少可以看到兩個錯誤。由於這顯然是一個學習練習,我建議你自己找到並修復它們......'因爲這是你需要開發的一項重要技能。我建議您使用IDE的調試器運行程序,並通過代碼「單步執行」來查看它在做什麼。