2014-10-20 168 views
-2

即時嘗試使一個方法返回短語中的字母數爲n個字母。我不斷收到字符串索引超出範圍:-1錯誤索引超出範圍錯誤-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; 
     } 
    } 
+7

請勿轉述錯誤消息。完全複製它。 – 2014-10-20 02:43:13

+1

爲什麼不與我們分享錯誤的堆棧跟蹤?(這是我的另一個$ 1「我得到和錯誤,但我不包括它」基金) – John3136 2014-10-20 02:43:28

+0

phrase3 = phrase3.substring(1);你可以expalin這條線嗎? – 2014-10-20 02:44:10

回答

0

當phrase3爲空字符串,你會得到一個錯誤。

phrase3.indexOf(" ") == -1 != 0 

所以這個條件通過。

然後子字符串函數失敗。

0

他們是你的問題行的兩個問題。

  • 在Java中,字符串索引從0開始。當您的字符串少於1個字符時,您會收到錯誤IndexOutOfBoundsException
  • 贊Petar寫道,indexOf返回-1當在字符串中找不到發生。基於你似乎想達到的目標,你應該檢查== -1而不是== 0

爲了簡化您的代碼,您應該考慮使用split()