如何查找数组java的Max,Min和Average

时间:2013-12-06 07:04:17

标签: java arrays max min average

我遇到了部分D-从平均值中找到最大值和最小值的问题。需要帮助能够计算平均值后的最小值和最大值。

我需要编写一个程序

  • 我的样本量
  • 对于4个试验中的每一个,每个试验的每个样品的数据都读入
  • 以表格格式打印每个样本的每个错误

    // Table header line
    System.out.println("\tSample #\tTrial 1\tTrial 2\tTrial 3\tTrial 4");
    
  • 打印每个案例的平均值,并通过比较使用最小值和最大值的平均值来计算试验彼此之间的匹配程度。

匹配最小值和最大值意味着试验完全匹配 - 试验完全匹配! 如果最大值小于最小值的两倍,则试验彼此一致 - “试验相互吻合!”否则试验之间的差异也是如此 高,他们不相互同意 - 审判 不要同意!

这就是我到目前为止......

public static void main(String[] args) {
    // TODO Auto-generated method stub

    Scanner input = new Scanner(System.in);


    //---Get the sample size

    System.out.print("Please enter the sample size: ");
    int max = input.nextInt();

    int[]arr0 = new int [max+1];
    int[]arr1 = new int [max+1];
    int[]arr2 = new int [max+1];
    int[]arr3 = new int [max+1];


    int count = 0, total = 0, num;

    {
        System.out.println("Enter numbers for Trial 0");
        for (int j = 0; j < max; j++) {
            System.out.print("Enter sample #" + j + ":");
            num = input.nextInt();
            if (num > 0) {
                arr0[j] = num;
                total += num;

            count++;
            arr0[max] = total/count;
        }

    }
}
    System.out.println("");

    //----------------------------------------

    int count1 = 0, total1 = 0, num1;

    {
        System.out.println("Enter numbers for Trial 1");
        for (int j = 0; j < max; j++) {
            System.out.print("Enter sample #" + j + ":");
            num1 = input.nextInt();
            if (num1 > 0) {
                arr1[j] = num1;
                total1 += num1;

            count1++;
            arr1[max] = total1/count1;
            }
        }

    }

    System.out.println("");

    //----------------------------------------

    int count2 = 0, total2 = 0, num2;

    {
        System.out.println("Enter numbers for Trial 2");
        for (int j = 0; j < max; j++) {
            System.out.print("Enter sample #" + j + ":");
            num2 = input.nextInt();
            if (num2 > 0); {
                arr2[j] = num2;
                total2 += num2;


                count2++;
                arr2[max] = total2/count2;
            }

        }
    }

    System.out.println("");

    //----------------------------------------

    int count3 = 0, total3 = 0, num3;

    {
        System.out.println("Enter numbers for Trial 3");
        for (int j = 0; j < max; j++) {
            System.out.print("Enter sample #" + j + ":");
            num3 = input.nextInt();
            if (num3 > 0); {
                arr3[j] = num3;
                total3 += num3;

                count3++;
                arr3[max] = total3/count3;

            }

        }

    }

    System.out.println("");


    // Table header line

    System.out.println("\tSample    #\tTrial    1\tTrial    2\tTrial    3\tTrial    4"); 
    for (int j = 0; j < max; j++) {
        System.out.print("\t" + j + "\t\t" + arr0[j] + "\t\t" + arr1[j]);
        System.out.println("\t\t" + arr2[j] + "\t\t" + arr3[j]);
    }


    //System.out.println("");   

    System.out.println("\t----------------------------------------------------------------------"); 

    //---Print out the average for each trial



    System.out.print("Average:\t\t" + arr0[max] + "\t\t" + arr1[max]);
    System.out.println("\t\t" + arr2[max] + "\t\t" + arr3[max]);



    // Figure out how closely the trials match with each other by comparing the averages using min and max

    System.out.println(" ");

    {
        if (arr1[max] == arr2[max]) {
            System.out.print("** The trials match EXACTLY! **");
        }
        if (arr1[max] > arr2[max]) {
            System.out.print("** The trials concur with each other! **");
        }
        if (arr1[max] < arr2[max]) {
            System.out.print("** The trials do NOT concur! **");
        }


    }


}

}

2 个答案:

答案 0 :(得分:0)

我想你可能想看看你的'min'变量。据我所知,你没有宣布它。你访问它一次(130行左右),但没有任何东西写入它。

答案 1 :(得分:0)

我不理解比较试验的逻辑......

我确实创建了一个示例,我最终得到了5个可用于比较逻辑的数组:

// Array to store the trials
int[][] trials = new int[numTrials][num];
// Array to store the stats (min, max, avg)
float[][] stats = new float[numTrials][3];

// Results
float[] minima = new float[numTrials]; // contains the minimum of all trials
float[] maxima = new float[numTrials]; // contains maxima of all the trials
float[] averag = new float[numTrials]; // averages of all the trials

如果你解释比较跑步的逻辑,我可以帮助你。 这就是我现在要生成的5个阵列,你似乎也需要它,也许它对你有所帮助:

public static void main(String[] args) {

    // Number of Trials
    int numTrials = 4;

    //---Get the sample size
    Scanner input = new Scanner(System.in);
    System.out.print("Please enter the sample size: ");
    int num = input.nextInt();
    input.nextLine();

    // Create explanation txt
    StringBuilder explain = new StringBuilder();
    for (int j = 0; j < num; j++) {
        if (explain.length() <= 0)
            explain.append("" + j);
        else
            explain.append("," + j);
    }

    // Array to store the trials
    int[][] trials = new int[numTrials][num];

    // Array to store the stats (min, max, avg)
    float[][] stats = new float[numTrials][3];

    // For the number of trials
    for (int i = 0; i < numTrials; i++) {

        // Define min,max, avg
        float min = Integer.MAX_VALUE;
        float max = Integer.MIN_VALUE;
        float avg = 0;

        // Ask for a trial run
        System.out.println("Enter numbers for Trial " + (i + 1) + " (e.g. " + explain.toString() + "):");
        String line = input.nextLine();
        String[] nums = line.split(",");

        /**
         * Extra check, to make sure user does not enter something like:
         * 'hallo'
         */
        while (nums.length != num) {

            // Tell User we did not receive the numbers we expected, and let them try again
            System.err.println("Invalid input. You have to enter " + num + " number, but we received only " + nums.length + " ! please try again");
            System.out.println("Enter numbers for Trial " + (i + 1) + " (e.g. " + explain.toString() + "):");

            // Read the input
            line = input.nextLine();

            // Split input on ',' character
            nums = line.split(",");
        }

        for (int n = 0; n < nums.length; n++) {
            int value = 0;
            try {
                // Get the input as a string
                String userInput = nums[n];

                // Strip any spaces etc from the string
                userInput = userInput.trim().replace(" ", "");

                // Try to parse the String to an integer
                value = Integer.parseInt(userInput);
            } catch (Exception e) {
            }

            // Minimum
            if (value < min)
                min = value;
            stats[i][0] = min;

            // Maximum
            if (value > max)
                max = value;
            stats[i][1] = max;

            // Avg
            avg = ((avg * n) + value) / (n + 1);
            stats[i][2] = avg;

            trials[i][n] = value;
        }
    }

    System.out.println("");

    // Table header line
    System.out.println("\tSample    #\tTrial    1\tTrial    2\tTrial    3\tTrial    4");
    for (int n = 0; n < num; n++) {
        System.out.print("\t" + n);
        for (int i = 0; i < numTrials; i++) {
            System.out.print("\t\t" + trials[i][n]);
        }
        System.out.println();
    }

    System.out.println("\t----------------------------------------------------------------------");

    String[] txts = { "min", "max", "avg" };
    for (int n = 0; n < txts.length; n++) {
        System.out.print("\t" + txts[n]);
        for (int i = 0; i < numTrials; i++) {
            //System.out.print("\t\t" + stats[i][n]);
            System.out.printf("\t\t%.2f", stats[i][n]);
        }
        System.out.println();
    }

    System.out.println("\t----------------------------------------------------------------------");

    float[] minima = new float[numTrials];
    float[] maxima = new float[numTrials];
    float[] avergs = new float[numTrials];
    for (int n = 0; n < numTrials; n++) {
        minima[n] = stats[n][0];
        maxima[n] = stats[n][1];
        avergs[n] = stats[n][2];
    }

    // Now, you can easily loop through all minima to compare
}

以下是运行上述代码的输出:

Please enter the sample size: 2
Enter numbers for Trial 1 (e.g. 0,1):
1,2
Enter numbers for Trial 2 (e.g. 0,1):
2,3
Enter numbers for Trial 3 (e.g. 0,1):
0,2
Enter numbers for Trial 4 (e.g. 0,1):
1,2

    Sample    # Trial    1  Trial    2  Trial    3  Trial    4
    0       1       2       0       1
    1       2       3       2       2
    ----------------------------------------------------------------------
    min     1.00        2.00        0.00        1.00
    max     2.00        3.00        2.00        2.00
    avg     1.50        2.50        1.00        1.50
    ----------------------------------------------------------------------