如何在多维数组(java)上求出总平均值

时间:2019-04-01 23:25:04

标签: java multidimensional-array average

我对Java还是很陌生,这项家庭作业使我感到困惑。我应该在一周的每一天中的一天中的4个不同时间打印2D高温数组,然后获得时间平均值,日平均值和总平均值。除了总平均值,我已经能够得到所有东西。我已经尝试了很多不同的方法,但无法使其正常工作。我知道我需要创建某种total_sum变量,以便可以将其除以得到总平均值,但是我不知道该怎么做。有人告诉我需要将其放在嵌套循环之外,就像我声明sum一样。 我知道这可能是一个愚蠢/基本的问题。

package com.company;

public class Temperatures {

  public static void main(String[] args) {
    System.out.println("Temperature Calculator");
    System.out.println("The data provided are: ");
    int[][] temps = new int[4][7];
    temps[0][0] = 68;
    temps[0][1] = 70;
    temps[0][2] = 76;
    temps[0][3] = 70;
    temps[0][4] = 68;
    temps[0][5] = 71;
    temps[0][6] = 75;
    temps[1][0] = 76;
    temps[1][1] = 76;
    temps[1][2] = 87;
    temps[1][3] = 84;
    temps[1][4] = 82;
    temps[1][5] = 75;
    temps[1][6] = 83;
    temps[2][0] = 73;
    temps[2][1] = 72;
    temps[2][2] = 81;
    temps[2][3] = 78;
    temps[2][4] = 76;
    temps[2][5] = 73;
    temps[2][6] = 77;
    temps[3][0] = 64;
    temps[3][1] = 65;
    temps[3][2] = 69;
    temps[3][3] = 68;
    temps[3][4] = 70;
    temps[3][5] = 74;
    temps[3][6] = 72;


    for (int row = 0; row < 4; row++) {
        String[] times = {"7 AM: ", "3 PM: ", "7 PM: ", "3 AM: "};
        System.out.print(times[row] + " ");
        for (int column = 0; column < 7; column++) {
            System.out.print(temps[row][column] + " ");
        }
        System.out.println();
    }
    System.out.println(" ");

    System.out.println("Based on that data, the following are the average temperatures for the week.");

    int sum;
    for (int column = 0; column < temps[0].length; column++) {
        String[] days = {"Sun: ", "Mon: ", "Tue: ", "Wed: ", "Thu: ", "Fri: ", "Sat: "};
        System.out.print(days[column]);
        sum = 0;
        for (int row = 0; row < temps.length; row++) {
            sum += (temps[row][column]);
        }
        int average = sum / temps.length;
        System.out.println(average);
    }
    System.out.println();

    for (int row = 0; row < temps.length; row++) {
        String[] times = {"7 AM: ", "3 PM: ", "7 PM: ", "3 AM: "};
        System.out.print(times[row]);
        sum = 0;
        for (int column = 0; column < temps.length; column++) {
            sum += (temps[row][column]);
        }
        int average = sum / temps.length;
        System.out.println(average);
    }
  }
}

2 个答案:

答案 0 :(得分:0)

我会尝试嵌套循环。像这样的东西。

Phase #

如果您确定每一行都有相同的列数,则可以执行

int sum = 0;
int indexCounter = 0; // Use this to keep track of the number of 'entries' in the arrays since they may not be perfectly rectangular.
for(int column = 0; column < temps.length; column++) {
    for(int row = 0; row < temps[column].length; row++) {
        sum+= temps[column][row];
        indexCounter++;
    }
}
int average = sum / indexCounter;
System.out.println("The average is " + average);

答案 1 :(得分:0)

这也可以用流,矩阵转置和计算小计的函数的Java 8方式完成。

public class FunctionalMatrixOps<T>
{
UnaryOperator<List<List<T>>> transposeList=m-> {
    List<Iterator<T>> iterList=m.stream().map(List::iterator).collect(Collectors.toList());
    return IntStream.range(0, m.get(0).size())
            .mapToObj(i->iterList.stream().filter(it->it.hasNext())
                    .map(item->item.next()).collect(Collectors.toList())).collect(Collectors.toList());
};

Function<T[][] , List<List<T>>> toList = array ->
Arrays.stream(array)
.map(row -> Arrays.stream(row).collect(Collectors.toList()))
.collect(Collectors.toList());

BiFunction<List<List<T>>,Class<T>, T[][]> toArray = (list,type)->
    list
    .stream()
    .map(row -> row.toArray((T[]) Array.newInstance(type, 0)))
    .collect(Collectors.toList())
    .toArray((T[][]) Array.newInstance(type, 0, 0));

BiFunction<T[][], Class<T>, T[][]> transposeMatrix= 
        (m,type)->toArray.apply(toList.andThen(transposeList).apply(m),type);

Function<Integer[][], List<Integer>> subTotals = 
        matrix->
        IntStream.range(0, matrix.length)
        .mapToDouble(i->Arrays.stream(matrix[i])
                .mapToDouble(Double::new)
                .average().getAsDouble())
        .mapToInt(ii->new Integer((int)ii))
        .boxed().collect(Collectors.toList());
}

您可以像这样调用以下Java 8函数:

FunctionalMatrixOps<Integer> tc=new FunctionalMatrixOps<Integer>();
    System.out.println("Temperature Calculator");    
List<Integer>avgByHour=tc.subTotals.apply(temps); 
System.out.println("Avg by Hour " + avgByHour);
List<Integer>avgByDayOfWeek=tc.subTotals.apply(tc.transposeMatrix.apply(temps, Integer.class));
System.out.println("Avg by Date of Week " + avgByDayOfWeek);
int avgTotal= (int) avgByHour.stream().mapToDouble(Double::valueOf).average().getAsDouble();
System.out.println("Avg Total (h) " + avgTotal);
int avgTotal2= (int) avgByDayOfWeek.stream().mapToDouble(Double::valueOf).average().getAsDouble();
System.out.println("Avg Total (dow) " + avgTotal2);
}