我如何继续获取声明的数组中的所有数字,然后得到长度,即其中有多少个数,然后除以它以找到其中所有数字的平均值。
package students;
import java.util.ArrayList;
public class students {
private ArrayList<Integer> scores = new ArrayList<Integer>();
private String name;
private int testScore;
public students(){
name = null;
testScore = 0;
}
public students(String s, int t){
name = s;
testScore = t;
}
public void addQuiz(int t){
scores.add(t);
}
public void averageGrade(){
//get all the scores in the array and divide by the amount for average grade
}
}
Theres my code
答案 0 :(得分:1)
从Java 8开始,有一种计算平均值的方法:
http://docs.oracle.com/javase/8/docs/api/java/util/DoubleSummaryStatistics.html#getAverage--
可以在此处找到相应的整数版本:
http://docs.oracle.com/javase/8/docs/api/java/util/IntSummaryStatistics.html#getAverage--
答案 1 :(得分:0)
public void averageGrade() {
int sum = 0;
float average = 0.0f;
for(int i = 0; i < scores.size(); i++)
sum += scores.get(i); // Compute total score
average = (float)sum / scores.size(); // Compute average
System.out.println(average);
}