这个小项目由两个类和一个ArrayList组成。ArrayList有两个元素:`name`和`score`。能否找出`score`元素的平均值?
`classroom`类:
`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
方法返回的学生分数,并将其除以数组大小?