0

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".

2
  • Given the input KMH_Kevin Magnussen_HAAS FERRARI, what is the name and what is the team? Commented Dec 12, 2019 at 4:52
  • Kevin Magnussen - name, HAAS FERRARI - team Commented Dec 12, 2019 at 4:56

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.