簡體   English   中英

Java-打印用戶輸入的4個整數,以及最低,最高和平均數

[英]Java - print user input of 4 integers, and the lowest, highest and average number

該程序應該接受四個等級的用戶輸入,選取這些等級並計算它們的最低,最高和平均水平。 然后,它需要打印出四個等級,以及帶有適當標簽的最低,最高和平均等級。 我無法弄清楚如何用我的代碼打印出四個等級,並且由於某種原因,它在每次循環迭代或每個用戶輸入之后都打印出最低,最高和平均水平。

這是我到目前為止的內容:

公共課程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);
    } } }

誰能幫我這個? 我需要它打印出四個等級(用戶輸入),以及四個等級的最低,最高和平均等級,但僅一次,而不是在循環的每次迭代之后。 抱歉,我的代碼看起來不好。

您只需在主方法中調用一次Test2(double grade)方法,因為Test2方法內部有一個for循環。 即在主外部調用Test2方法進行循環。

您的答案應該是下面的課程。

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);


}

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM