Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1 at java.lang.String.substring(String.java:1960)

I have the class Racer :

public class Racer {

private String name;
private String team;
private String result;


public Racer(String name, String team) {
    this.name = name;
    this.team = team;
}

@Override
public String toString() {
    return "Racer{" +
            "name='" + name + '\'' +
            ", team='" + team + '\'' +
            ", result='" + result + '\'' +
            '}';
}}

Then, I tried to create racer of this class in another Class :

public class RacerList {
public void createListOfRacers() {
Racer Kevin = createRacer("KMH_Kevin Magnussen_HAAS FERRARI");
}

And such methods to help creating racer :

 private Racer createRacer(String line) {
    return new Racer(extractNameOfTheRacer(line), extractTeamOfTheRacer(line));
}

private String extractNameOfTheRacer(String line) {
    return line.substring(line.indexOf('_' + 1), line.lastIndexOf('_'));
}

private String extractTeamOfTheRacer(String line) {
    return line.substring(line.lastIndexOf('_' + 1));
}

}

I received indicated Error here :

return line.substring(line.indexOf('_' + 1), line.lastIndexOf('_'));

in the method "extractNameOfRacer".

Upvotes: 0

Views: 223

Answers (2)

lakshman
lakshman

Reputation: 2741

You are getting index of '_'+1 of the string which is evaluate to 96 as int which is bigger than your actual string length. Change this line

line.substring(line.indexOf('_' + 1), line.lastIndexOf('_'));

to

line.substring(line.indexOf('_') +1, line.lastIndexOf('_'));

to get the string between first underscore and last underscore

Upvotes: 1

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521579

Honestly I would recommend that you just use String#split here and make your life easy:

private Racer createRacer(String line) {
    return new Racer(line.split("_")[1], line.split("_")[2]);
}

The cause of your current issue is that you aren't using substring properly. But, I would avoid it entirely and use split instead.

Upvotes: 0

Related Questions