2014-10-20 143 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()