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



我被问到的问题是:

开发一个应用程序,从用户那里接收四周内每天的平均降雨量,并将其存储在一个数组中。然后,应用程序应该计算每周的平均降雨量,并将答案存储在一个单独的数组中。然后,应用程序应该向用户输出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);
       }
    }

使用流可以做到这一点。

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

问题出在下一行:

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];)也是如此。您可能需要为计算使用额外的循环。

您可以只使用一维数组表示平均值,这将消除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

不是我不喜欢其他的答案,我喜欢,我只是觉得你应该得到一个解释,在你的好的尝试中哪里出错了。

相关内容

  • 没有找到相关文章

最新更新