UML:
-name: String
-playerId: int
-scores: int[]
-bestScore: int
-numberOfPlayers: int
<< constructors>>
+Player()
+Player(name: String)
<< set methods>>
+setName(name: String):void
+setScores(score: int[]):void
<< get methods >>
+getPlayerId():int
+getName():String
+getScores():int[]
+getBestScore(): int
+calculateAverage(): double
<< helper methods >>
-calculateBestScore(): void
任何想法我应该如何设置numberOfPlayers赋值给playerId? 我如何进行calculateAverage和calculateBestScore方法?
目前我的代码是:
//Class declaration of Player class
public class Player
{
/*--------------- Data Fields --------------------------------------
Attributes of the class
*/
private String name;
private int playerId;
private int bestScore;
private int numberOfPlayers;
private int scores;
/* -------------- CONSTRUCTOR --------------------------------------
*/
public Player(String name)
{
this.name = name;
this.numberOfPlayers = numberOfPlayers + 1;
this.playerId = this.numberOfPlayers;
}
//Create set method for setName
public void setName(String name)
{
this.name = name;
}
//Create set method for setScores
public void setScore(int score)
{
scores = score;
}
//Create get method for getPlayerId
public int getPlayerId()
{
return playerId;
}
//Create get method for getName
public String getName()
{
return name;
}
//Create get method for getScores
public int getScores()
{
return scores;
}
//Create get method for getBestScore
public int getBestScore()
{
return bestScore;
}
//Create get method for calcualteAverage
public double calculateAverage()
{
}
}
答案 0 :(得分:0)
构造函数将增加静态变量numberOfPlayers,然后将numberOfPlayers的值赋给playerId
为您的变量提供static
标识符,并初始化它:
private static int numberOfPlayers = 0;
每次创建新的Player类时,请将其递增1:
public Person() {
numberOfPlayers++;
}
您需要一种方法来公开numberOfPlayers的值,并将其设为static
,以便任何Player类都可以调用它:
public static int getNumPlayers() {
return numberOfPlayers;
}
测试它是一种有效的方法:
Person a = new Person();
Person b = new Person();
Person c = new Person();
System.out.println(c.getNumPlayers()); //will be 3 based on the above
关于分数的计算,您的getScores
和setScore
方法会有问题。首先,getScores
意味着您必须返回多个分数。其次,setScore
让我想知道你必须为一个玩家多少次这样做,并且当你在一系列分数中增长时,你会在哪里存储价值?我觉得对我来说太过雄心勃勃,无法猜测可能满足你需求的不同方法。如果这是学校作业,请咨询教师。我将分享使用ArrayList
数据结构的这种方法:
private ArrayList<Integer> scores = new ArrayList<Integer>();
public Person() {
}
public void setScore(int score) {
scores.add(score);
}