1

This is my method to updateHighScoreRecords():

    public GameRecord[] updateHighScoreRecords(GameRecord[] highScoreRecords, String name, int level, int score) {
    GameRecord[] gameRecord = null;

    if (highScoreRecords.length == 0) {     // Rule one
        gameRecord = new GameRecord[1];
        gameRecord[0].setName(name);
        gameRecord[0].setLevel(level);
        gameRecord[0].setScore(score);
        System.out.println("Role one Done");
    }
    return gameRecord;
}

And this is my GameRecord class:

public class GameRecord {
private String name;
private int level;
private int score;

public GameRecord(String name, int level, int score) {

    this.name = name;
    this.level = level;
    this.score = score;
}
public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}
public int getLevel() {
    return level;
}
public void setLevel(int level) {
    this.level = level;
}

public int getScore() {
    return score;
}

public void setScore(int score) {
    this.score = score;
}
}

But there is a nullPointer exception on this line:

gameRecord[0].setName(name);

Why?

I want to return an array of GameRecord type when highScoreRecords length is zero.

2

1 Answer 1

4

You never initialized zeroth element. First you have to add element at zero position and then access it.

 gameRecord[0] = new GameRecord();
 gameRecord[0].setName(name);

When you wrote

  gameRecord = new GameRecord[1];

That means you are just initializing an array to store 2 GameRecord elements. Nothing else. Initially those are null's. You need to initialize each element to use them further. Otherwise they are still null.

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

Comments

Your Answer

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