如何增加所有对象的价值? [英] How to add the value of all the objects?

查看:44
本文介绍了如何增加所有对象的价值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比方说我们有一个SCORE课程.它具有三个对象s1,s2和s3. SCORE具有属性RUNS.如何添加所有对象的运行? SCORE具有内部方法int TOTALSCORE().因此,在调用该方法时,它应该返回总得分.

Let's say we have a class SCORE. It has three objects s1,s2 and s3. SCORE has an attribute RUNS. How to add the runs of all the objects ? SCORE has an internal method int TOTALSCORE(). so when that method is called, it should return the total score .

我应该如何调用该方法?像s1.TOTALSCORE()吗?还是其他方式?

How should i call that method ? Like s1.TOTALSCORE() ? Or any other way?

推荐答案

在极少数情况下,您想要的东西可能是合理的,但通常情况下,该类并不了解其所有元素.总分是分数元素的集合,可能是列表或集合.

In rare cases the thing that you want could be reasonably, but normally the class is not aware of all it's elements. A total Score is for a Collection of Score elements, maybe a List or a Set.

所以您会这样做:

class Score {
  int value;
  // ...
  public static int totalScore(Collection<Score> scores){ 
    int sum = 0;
    for (Score s: scores){
      sum += s.value;
    }
    return sum;
  }
}

在外面你会拥有

List<Score> myBagForScores = new ArrayList<>();
Score e1 = new Score...
myBagForScores.add(e1);
// e2, e3 and so on
int sum = Score.totalScore(myBagForScores);

希望有帮助!

这篇关于如何增加所有对象的价值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆