我正在开发一个程序,允许用户在四支球队之间选择主客场足球队。我创建了一个通用的 super 团队,定义了每个安全/射门得分/达阵分配的分数。生成一个随机数,然后根据该数字,程序逐步执行条件 if/else 语句以确定操作和点。
这是在父类(super class)中:
public void possessionPoints()
{
if(points<lowNopoints){
score = noPoints;
totalScore = totalScore + score;
System.out.println("No points, plus " + score);
}
else if(points<lowSafetypoint){
score = safetyPoint;
totalScore = totalScore + score;
System.out.println("Safety, plus" + score);
}
else if(points<lowFieldgoal){
score = fieldGoal;
totalScore = totalScore + fieldGoal;
System.out.println("Field goal, plus" + score);
}
else{
score = touchDown;
totalScore = totalScore + touchDown;
System.out.println("Touchdown, plus" + score);
}
ArrayList<Integer> totalScore;
totalScore = new ArrayList<>();
totalScore.add(score);
//the sum score
int sum = totalScore.stream().mapToInt(Integer::intValue).sum();
System.out.println("Current score is: " + sum);
}
注:以上 totalScore
初始化为public static int totalScore = 0;
在整个过程中,我想跟踪 totalScore
。我在我的父类(super class)中有这样的设置,但是,当程序运行时,它会将整个游戏的得分相加,并且不会区分团队。
Output:
Home team action. No points, plus 0 Current score: 0
Away team action. Field goal, plus3 Current score: 3
Home team action. Field goal, plus3 Current score: 6
Away team action. Field goal, plus3 Current score: 9
Home team action. Safety, plus2 Current score: 11
另外,如果有帮助的话,这就是我在下面其他团队的每个子类中设置的全部内容。我没有对totalScore
做任何事情.
public class PackersSub extends GenericSuper{
public PackersSub()
{
lowNopoints = 4;
lowSafetypoint = 5;
lowFieldgoal = 7;
}
关于如何解决此问题有什么想法吗?我想跟踪totalScore
每个团队。谢谢!
最佳答案
如果您想在每个团队级别进行跟踪,那么您应该将其定义为成员变量,以便每个团队都有自己的 totalScore
字段副本。
在父类(super class)中归档static
意味着它将始终是子类中发生的所有操作的总聚合。因为每个类只维护一份静态字段的副本。在您的情况下,您已在父类(super class)中定义了它,这使其成为分数聚合的全局字段。
关于java - 区分父类(super class)和子类之间的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34252346/