当前位置: 首页 > 知识库问答 >
问题:

请帮助粘在这个UML图上

汪永春
2023-03-14
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
    null

有任何想法,我应该如何设置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()
        {
        }
        }

共有1个答案

仰城
2023-03-14

构造函数将增加静态变量numberOfPlayers,然后将numberOfPlayers的值分配给playerId

为变量提供static标识符,并初始化它:

private static int numberOfPlayers = 0;

每次创建新的Player类时,将其递增1:

public Person() {
    numberOfPlayers++;
}
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
private ArrayList<Integer> scores = new ArrayList<Integer>();

public Person() {

}

public void setScore(int score) {
    scores.add(score);
}
 类似资料: