0

The assignment I have is to find the average of the temps in each row of the array. There are 3 rows. I have to find the average of the 3 rows separately, not together, and then print out the averages like so:

Avg for student 1 is x
Avg for students 2 is A
Avg for student 3 is h.

This is the actual assignment paper:

Name this program testScoresArray. Write a program that stores the following temps in a 2D array.

Student 1: 100, 80, 93
Student 2: 74, 83, 91, 87
Student 3: 94, 98

Find the average temp for EACH student separately. Hint: you need to keep track of the score but after every time it loops through a column and finds the average, you need to set the value of the score back to 0 or it will count the previous scores!

EXAMPLE:

Average temp for Student 1: 91.0
Average temp for Student 2: 83.75
Average temp for Student 3: 96.0 

This is the code I have right now. I need to find a way to find the averages separately and print them the way above. I can't seem to do that. Can anyone help me, please?

public class testScoresArray {
    public static void main(String args[]) {
        int[][] temps = {{100, 80, 93}, {74, 83, 91, 87}, {94, 98}};
        for (int i = 0; i < temps.length; i++) {
            int sum = 0;
            for (int g = 0; g < temps[i].length; g++) {
                sum += temps[i][g];
            }
            System.out.println(sum / temps[i].length);
            System.out.println();
        }
    }
}

2 Answers2

0

Not the best, but the easiest solution would be to simply change the type of sum to float or double

float sum = 0;

This will make the division that happens on the println to change from integer division to a floating point one, if only one of the operands has a floating point then your print will have a dot

Kolepcruz
  • 61
  • 5
0

Single-semicolon solution using streams:

int[][] temps = {{100, 80, 93}, {74, 83, 91, 87}, {94, 98}};
// iterating over row indices
IntStream.range(0, temps.length)
        // print the beginning of each row
        .peek(i -> System.out.print("Average temp for Student "+(i+1)+": "))
        // take the average of the row
        .mapToDouble(i -> Arrays.stream(temps[i]).average().orElse(0.0))
        // print the average value and the line break
        .forEach(System.out::println);

Output:

Average temp for Student 1: 91.0
Average temp for Student 2: 83.75
Average temp for Student 3: 96.0

See also: Searching for average temperature for all dates between two dates