Java StringIndexOutOfBoundsException:字符串索引超出范围:-1

Java StringIndexOutOfBoundsException:字符串索引超出范围:-1,java,Java,我在BlueJ中的代码很难使用。我不断地得到这个错误,所有语法和其他问题都得到了解决,但它不断地提供这个错误。上面写着在第22行: StringIndexOutOfBoundsException:字符串索引超出范围:-1 以下是我编写的代码: public static void main() { String songInfo = MediaFile.readString(); int index = songInfo.indexOf("|"); System.out.

我在BlueJ中的代码很难使用。我不断地得到这个错误,所有语法和其他问题都得到了解决,但它不断地提供这个错误。上面写着在第22行:

StringIndexOutOfBoundsException:字符串索引超出范围:-1

以下是我编写的代码:

public static void main() {
    String songInfo = MediaFile.readString();
    int index = songInfo.indexOf("|");
    System.out.println("My Favorites");
    System.out.println("------------");
    while(index > 0){
        String title = songInfo.substring(0, index);

        songInfo = songInfo.substring(index + 1);

        index = songInfo.indexOf("|");

        String ratingStr = songInfo.substring(0, index);  //this is the line where the error occurs
        int rating = Integer.valueOf(ratingStr);

        if(rating >= 8){
            System.out.println(title + "(" + rating + ")");
        }

        songInfo = songInfo.substring(index + 1);

        index = songInfo.indexOf("|");
    }

}

如何解决此问题?

在第20行,您拨打此电话:

index = songInfo.indexOf("|");
。。。第22行的错误是:

StringIndexOutOfBoundsException:字符串索引超出范围:-1

。。。告诉您
索引
为-1

这是因为当
indexOf
找不到您请求的字符串时,它返回-1。这意味着(正如Andy Turner所评论的)
songInfo
在程序的这一点上不包含
|

下一步要尝试什么:

  • 检查您的输入数据
  • 使用调试器并逐步完成代码
  • 适当地处理-1的索引

  • index
    的值是多少?
    songInfo
    在获取子字符串后不包含