2

I'm very new to Java, and this homework assignment is throwing me. I am supposed to print out a 2D array of high temperatures at 4 different times of the day on every day of the week, then get the time averages, the day averages, and the total average. I've been able to get everything except the total average. I have tried so many different things, and I cannot get it to work. I know I need to create some sort of total_sum variable so I can then divide it and get the total average, but I cannot figure out how. I've been told I need to put it outside of the nested loop, like how I declared sum. I know this is probably a dumb/basic question.

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);
    }
  }
}
Carlos Cavero
  • 3,011
  • 5
  • 21
  • 41
  • what exactly do you mean total average? Sum of all cells in the temp array divided by array size? – vs97 Apr 01 '19 at 23:33
  • Yes, an average for all the rows and columns (one number). – picturecharity Apr 01 '19 at 23:37
  • Possible duplicate of [How to find average of elements in 2d array JAVA?](https://stackoverflow.com/questions/40709464/how-to-find-average-of-elements-in-2d-array-java) – vs97 Apr 01 '19 at 23:40

2 Answers2

0

I would try nested for loops. Something like this..

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

If you knew for sure that each row had the same number of columns then you could do something like

 int average = sum / (temps.length * temps[0].length)
Zach Ehret
  • 38
  • 8
  • That worked! Oh my gosh, thank you so much! I have been going round and round for days. I knew I was making it harder than I needed to. – picturecharity Apr 01 '19 at 23:48
0

This can also be done java 8 way with streams and with transpose of a matrix and a function that calculates the subtotal.

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

You can call these java 8 functions like this:

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