如何使用从用户插入的值计算数组的平均值?

时间:2015-04-01 05:09:27

标签: java arrays average

我正试图让用户插入平均年龄。我试着询问班上有多少学生,他们的年龄是多少。之后,它按升序显示年龄,但是,我应该计算平均年龄。为什么你们认为我的程序不起作用? 任何反馈都可以帮助你们,并提前感谢你们。 (这是我想要它的大致轮廓) 对不起,如果我的代码没有正确插入。

package averageage;
import javax.swing.JOptionPane;
import java.util.ArrayList;
import java.util.List;
import java.util.Collections;

public class AverageAge {

    public static void main(String[] args) {
        int Avg = 0;
        int n = Integer
                .parseInt(JOptionPane
                        .showInputDialog("Enter number of how many people are in the classroom:"));
        n = n - 1;
        // * n is defined for the number of students-1 because a list starts at
        // 0.
        List<Integer> Ages = new ArrayList<>();
        // *Defined the list.
        for (int i = 0; i <= n; i++) {
            Ages.add(Integer.parseInt(JOptionPane
                    .showInputDialog("Enter the ages, program will stop at length limit.")));
        }
        Collections.sort(Ages);
        for (int counter : Ages) {
            JOptionPane.showMessageDialog(null,
                    "The ages in ascending order:\n" + counter);
        }
        n++;
    }

    // *Sets back the value of n to original input.
    public static int AverageAge(int[] Ages) {
        int sum = 0;
        for (int x = 0; x < Ages.length; x++) {
            sum = sum + Ages[x];
        }
        int Avg = sum / Ages.length;
        JOptionPane.showMessageDialog(null, "The average age is: \n" + Avg);
        return Avg;

    }
}

1 个答案:

答案 0 :(得分:0)

你没有调用AverageAge方法,我已经更改了代码。我希望这会起作用

package averageage;

import javax.swing.JOptionPane;
import java.util.ArrayList;
import java.util.List;
import java.util.Collections;

public class AverageAge {

public static void main(String[] args) {
    int Avg = 0;
    int n = Integer
            .parseInt(JOptionPane
                    .showInputDialog("Enter number of how many people are in the classroom:"));
    n = n - 1;
    // * n is defined for the number of students-1 because a list starts at
    // 0.
    List<Integer> Ages = new ArrayList<>();
    // *Defined the list.
    for (int i = 0; i <= n; i++) {
        Ages.add(Integer.parseInt(JOptionPane
                .showInputDialog("Enter the ages, program will stop at length limit.")));
    }
    /*Collections.sort(Ages);
    for (int counter : Ages) {
        JOptionPane.showMessageDialog(null,
                "The ages in ascending order:\n" + counter);
    }
    n++;*/
    AverageAge(Ages);
}

// *Sets back the value of n to original input.
public static int AverageAge(List<Integer> Ages) {
    int sum = 0;
    for (int x = 0; x < Ages.size(); x++) {
        sum = sum + Ages.get(x);
    }
    int Avg = sum / Ages.size();
    JOptionPane.showMessageDialog(null, "The average age is: \n" + Avg);
    return Avg;

 }
}