我不知道我的代码发生了什么,但在下面的程序中,我有一个传入UpdateHighScoreRecords()
函数的对象数组,它可以包含或不包含一些值。如果数组对象大小为零,我必须初始化highScoreRecords[0]
但它正在显示ArrayIndexOutOfBoundsException
。你能解决这个问题吗?
/**
* The GameRecord class represents a record for the a game play, including the name of the player, the level of the game play and the score obtained.
*/
public class GameRecord {
/** The name of the player. **/
private String name;
/** The level of the game play. **/
private int level;
/** The score of the game play. **/
private int score;
/**
* Constructs a game record with a certain name, level and score.
* @param name the name of the player.
* @param level the level of the game play.
* @param score the score of the game play.
*/
public GameRecord(String name, int level, int score) {
this.name = name;
this.level = level;
this.score = score;
}
/**
* Returns the name of the player in the record.
* @return the name of the player in the record.
*/
public String getName() {
return name;
}
/**
* Sets the name of the player in the record.
* @param name the name of the player to be updated to.
*/
public void setName(String name) {
this.name = name;
}
/**
* Returns the level of the game play in the record.
* @return the level of the game play in the record.
*/
public int getLevel() {
return level;
}
/**
* Sets the level of the game play in the record.
* @param level the level of the game play to be updated to.
*/
public void setLevel(int level) {
this.level = level;
}
/**
* Returns the score of the game play in the record.
* @return the score of the game play in the record.
*/
public int getScore() {
return score;
}
/**
* Sets the score of the game play in the record.
* @param score the score of the game play to be updated to.
*/
public void setScore(int score) {
this.score = score;
}
}
public GameRecord[] updateHighScoreRecords(GameRecord[] highScoreRecords, String name, int level, int score)
{
// write your code after this line
if(highScoreRecords.length == 0 )
{
highScoreRecords[0] = new GameRecord(name, level, score);
return highScoreRecords;
}
else if(highScoreRecords.length < 10)
{
int i=0;
while(i<highScoreRecords.length)
{
if(highScoreRecords[i].getName().equals(name))
{
if(highScoreRecords[i].getScore() < score )
{
highScoreRecords[i].setScore(score);
highScoreRecords[i].setLevel(level);
break;
}
break;
}
i++;
}
if(i == highScoreRecords.length)
{
highScoreRecords[i].setName(name);
highScoreRecords[i].setScore(score);
highScoreRecords[i].setLevel(level);
}
}
else if (highScoreRecords.length == 10)
{
int i=0;
while(i<highScoreRecords.length)
{
if(highScoreRecords[i].getName().equals(name))
{
if(highScoreRecords[i].getScore() < score )
{
highScoreRecords[i].setScore(score);
highScoreRecords[i].setLevel(level);
break;
}
break;
}
i++;
}
if(i == highScoreRecords.length)
{
highScoreRecords[9].setName(name);
highScoreRecords[9].setScore(score);
highScoreRecords[9].setLevel(level);
}
}
return highScoreRecords;
}