Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/366.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 索引超出范围错误-1(=和!=)_Java_String - Fatal编程技术网

Java 索引超出范围错误-1(=和!=)

Java 索引超出范围错误-1(=和!=),java,string,Java,String,我正在尝试使一个方法返回短语中n个字母长的单词数。我不断获取超出范围的字符串索引:-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

我正在尝试使一个方法返回短语中n个字母长的单词数。我不断获取超出范围的字符串索引:-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;
        }
    }

当phrase3为空字符串时,您将得到一个错误

phrase3.indexOf(" ") == -1 != 0
所以这个条件通过了


然后子字符串函数失败。

这是故障线路的两个问题

  • 在Java中,字符串索引从0开始。当字符串少于1个字符时,会出现错误
    IndexOutOfBoundsException
  • 与Petar编写的一样,在字符串中找不到出现项时返回
    -1
    。根据您似乎想要实现的目标,您可能应该检查
    ==-1
    ,而不是
    ==0

<>也要简化代码,你应该考虑使用.< /p>不要解释错误消息。完全复制。为什么不与我们共享错误的堆栈跟踪?。。。(这是我的“我得到和错误,但我不包括它”基金的另一个1美元)短语3=短语3.子字符串(1);你能解释一下这条线路吗?