计算一个数组列表的平均? [英] Calculating average of an array list?
本文介绍了计算一个数组列表的平均?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
code:
ArrayList <Integer> marks = new ArrayList();
Collections.addAll(marks, (Integer.parseInt(markInput.getText())));
private void analyzeButtonActionPerformed(java.awt.event.ActionEvent evt) {
analyzeTextArea.setText("Class average:" + calculateAverage(marks));
}
private int calculateAverage(List <Integer> marks) {
int sum = 0;
for (int i=0; i< marks.size(); i++) {
sum += i;
}
return sum / marks.size();
}
我试图用这个code来计算一组用户输入值的平均值,并在JTextArea显示,但它不能正常工作。比方说,用户输入7,4,和5,程序将显示1当它应该显示平均5.3
I'm trying to use this code to calculate the average of a set of values that a user enters and display it in a jTextArea but it does not work properly. Say, a user enters 7, 4, and 5, the program displays 1 as the average when it should display 5.3
什么是错的code?
谢谢!
推荐答案
为什么要用一个笨拙的for循环与索引当你有增强的for循环?
Why use a clumsy for loop with an index when you have the enhanced for loop?
private double calculateAverage(List <Integer> marks) {
Integer sum = 0;
if(!marks.isEmpty()) {
for (Integer mark : marks) {
sum += mark;
}
return sum.doubleValue() / marks.size();
}
return sum;
}
这篇关于计算一个数组列表的平均?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文