簡體   English   中英

如何在多維數組上找到總平均值(java)

[英]How to find a total average on a multidimensional array (java)

我是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);
    }
  }
}

我會嘗試嵌套循環。 像這樣

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

如果您確定每一行都有相同的列數,則可以執行以下操作

 int average = sum / (temps.length * temps[0].length)

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

暫無
暫無

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

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