Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
602 views
in Technique[技术] by (71.8m points)

java - How to add the value of all the objects?

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 .

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

So you would do:

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

And outside you would have

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

Hope that helps!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...