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
    Common Java rookie mistake: Instantiating an array does not instantiate the elements. – Ian McLaird Aug 07 '14 at 13:03
  • possible duplicate of [What is a Null Pointer Exception, and how do I fix it?](http://stackoverflow.com/questions/218384/what-is-a-null-pointer-exception-and-how-do-i-fix-it) – DavidPostill Aug 07 '14 at 13:04

1 Answers1

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.

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307