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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.