Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
765 views
in Technique[技术] by (71.8m points)

java - StringIndexOutOfBoundsException: String index out of range: -1

I'm having a hard time with my code in BlueJ. I keep getting this error, all syntax and other issues are solved, but it keeps on providing this error. It says it's in line 22:

StringIndexOutOfBoundsException: String index out of range: -1

Here's the code I've written:

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("|");
    }

}

How can I fix this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

On line 20, you make this call:

index = songInfo.indexOf("|");

... and the error from line 22:

StringIndexOutOfBoundsException: String index out of range: -1

... tells you that index was -1.

This is because when indexOf cannot find the string you request, it returns -1. This means (as Andy Turner commented) songInfo does not contain a | at this point in the program.

What to try next:

  1. Check your input data.
  2. Use a debugger and step through your code.
  3. Handle the index of -1 appropriately

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...