【发布时间】:2016-03-13 18:41:22
【问题描述】:
这个小项目由两个类和一个ArrayList组成。 ArrayList 有两个元素:name 和score。是否可以求元素score的平均值?
班级classroom:
/**
* This class creates the names and scores of the students
*/
public class Classroom
{
public int score;
public String name;
/**
* Constructor for the Class that adds a name and a score.
*/
public Classroom(String aName, int aScore)
{
score = aScore;
name = aName;
}
/**
* Return the name of the students
*/
public String returnName()
{
return name;
}
/**
* Return the scores
*/
public int returnScore()
{
return score;
}
}
班级TestScores:
import java.util.ArrayList;
/**
* Print test scrose and student names as well as he average for the class.
*/
public class TestScores
{
private ArrayList<Classroom> scores;
public int studentScores;
/**
* Create a new ArrayList of scores and add some scores
*/
public TestScores()
{
scores = new ArrayList<Classroom>();
}
/**
* Add a new student and a new score.
*/
public void add (String name, int score)
{
scores.add(new Classroom(name, score));
if(score > 100){
System.out.println("The score cannot be more than 100");
}
}
难道您不能使用 for each 循环,创建一个局部变量来存储来自课堂课堂中 returnScore 方法的学生分数,然后将其除以数组大小吗?
【问题讨论】:
-
您可以遍历ArrayList并找到所有分数,将它们相加计算平均值。
-
...或者使用 Java 8 流,这使得整个事情更加简洁。
-
我建议你三种方式,看我的回答
-
考虑将你的getter命名为getXxx,而不是returnXxx。