Java - 2D数组 - 每周需要平均值,无法弄清楚

时间:2016-10-15 14:20:28

标签: java arrays multidimensional-array

我被问到的问题是:

开发一个接受用户的应用程序,每天平均降雨量为四周,并将它们存储在一个数组中。然后,应用程序应计算每周的平均降雨量,并将答案存储在单独的阵列中。然后,应用程序应将4个平均值输出给用户。将该类保存为RainfallApp.java

这是我到目前为止所做的事情,我无法让它发挥作用。 -

    public class RainfallApp {
    // int[rows ←→][colums ↑↓] num = new int[][];
    public static void main(String[] args) {

    int[][] rain = new int[4][7]; //4 weeks, 7 days
    int[][] average = new int[4][1]; //4 weeks, 1 average of week
    int sum[] = new int[4]; //total rain per week 
    int i;
    int j;

    for (i = 0; i < rain.length; i++) {

        for (j = 0; j < rain[0].length; j++) {
            rain[i][j] = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter value")); //value 
        }
        sum[i] = sum[i] + rain[i][j]; //total of each week

        average[i][j] = sum[i]/rain[i][j];

    }


    JOptionPane.showMessageDialog(null, "The average for each week is: "+ average);

       }
    }

3 个答案:

答案 0 :(得分:1)

使用流可以做到这一点。

Stream.of(rain)
    .map(week -> IntStream.of(week).average())
    .filter(OptionalDouble::isPresent)
    .map(OptionalDouble::getAsDouble)
    .forEach(System.out::println);

更常规地,或者如果您需要周数,您可以这样做。

for (int weekNum = 1; weekNum <= rain.length; ++weekNum)
{
    OptionalDouble maybeAverage = IntStream.of(rain[weekNum-1]).average();
    if (maybeAverage.isPresent())
    {
        System.out.println("Average for week " + weekNum + ": " + maybeAverage.getAsDouble());
    }
}

答案 1 :(得分:0)

问题出在以下几行:

sum[i] = sum[i] + rain[i][j]; //total of each week

j == 7导致for循环停止执行,但您尝试访问不存在的rain[i][7]值。同样对于它后面的行(average[i][j] = sum[i]/rain[i][j];)。您可能希望使用额外的循环进行计算。

答案 2 :(得分:0)

你可以只使用1维数组进行平均,它将消除PEF指出的一些问题。

    int[][] rain = new int[4][7]; // 4 weeks, 7 days
    // use just a 1-dimensional array for average
    int[] average = new int[4]; // 4 weeks, 1 average of week
    int[] sum = new int[4]; // total rain per week
    int i;
    int j;

    for (i = 0; i < rain.length; i++) {

        for (j = 0; j < rain[0].length; j++) {
            rain[i][j] = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter value")); // value
            // to add each day’s rainfall, do it inside the loop
            sum[i] = sum[i] + rain[i][j]; // total of each week
        }

        // obtain average by dividing by number of days
        average[i] = sum[i] / rain[i].length;

    }

    // just printing out an array doesn’t give meaningful output. use: 
    JOptionPane.showMessageDialog(null, "The average for each week is: " + Arrays.toString(average));

如果您更喜欢平均2D阵列,只需使用average[i][0]来读取和写入元素。您可能希望在分割前将总和转换为double,以避免将值截断为int

并不是我不喜欢其他答案,我知道,我只是觉得你应该解释你的不良尝试中出了什么问题。