Java - 打印4个整数的用户输入,以及最低,最高和平均数

时间:2017-02-04 18:33:39

标签: java arrays for-loop

该程序应该用户输入四个等级,取这些等级并计算它们的最低,最高和平均值。然后它需要打印出四个等级以及最低,最高和平均值,并带有适当的标签。我无法弄清楚如何使用我的代码打印出四个等级,并且出于某种原因,它会在循环的每次迭代或每个用户输入后打印出最低,最高和平均值。

这是我到目前为止所做的:

public class Test2 {

double total = 0.0;
double max = 0.0;
double min = Double.MAX_VALUE;

public void Test2 (double[] grades){
//Loop through all of the grades.
for(int i = 0; i < 4; i++){

    double grade = grades[i];
    //Add the grade to the total
    total += grade;

    //If this is the highest grade we've encountered, set as the max.
    if(max < grade){
        max = grade;
    }
    //If this is the lowest grade we've encountered, set as min.
    if(min > grade){
        min = grade;
    }
}
    System.out.println("Average is: " + (total / 4));
    System.out.println("Max is: " + max);
    System.out.println("Min is: " + min); }

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    double[] grades = new double[4];

    System.out.println("Please enter number");

    for (int i = 0; i < grades.length; i++) {
        grades[i] = input.nextDouble();
        Test2 g = new Test2();
        g.Test2(grades);
    } } }

任何人都可以帮我吗?我需要它打印出四个等级(用户输入),以及四个等级中的最低,最高和平均等级,但仅限于一次,而不是在循环的每次迭代之后。对不起,如果我的代码看起来很糟糕。

2 个答案:

答案 0 :(得分:2)

您必须在main方法中只调用一次方法Test2(double grade),因为Test2方法中存在for循环。即在主外部调用Test2方法进行循环。

答案 1 :(得分:0)

您的答案应该是以下课程。

import java.util.Scanner;

public class Test2 {

double total = 0.0;
double max = 0.0;
double min = Double.MAX_VALUE;

public void doOperations(double[] grades) {
    for (int i = 0; i < 4; i++) {

        double grade = grades[i];
        //Add the grade to the total
        total += grade;

        //If this is the highest grade we've encountered, set as the max.
        if (max < grade) {
            max = grade;
        }
        //If this is the lowest grade we've encountered, set as min.
        if (min > grade) {
            min = grade;
        }
    }
    System.out.println("Average is: " + (total / 4));
    System.out.println("Max is: " + max);
    System.out.println("Min is: " + min);
}

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    double[] grades = new double[4];

        System.out.println("Please enter number");

        for (int i = 0; i < grades.length; i++) {
            grades[i] = input.nextDouble();
        }
        Test2 test2 = new Test2();
        test2.doOperations(grades);


}

}