I have a 2D array of 4 tests, 5 scores a piece. I need to print the average out with which test number it belongs to. I also need the tests numbers to be 1-4 instead of 0-3.
I'm unsure of how to renumber the tests and get it to print a readable number:
int[][] testScores = {
{100, 85, 91, 75, 82},
{81, 75, 68, 92, 87},
{99, 71, 75, 84, 91},
{97, 91, 68, 72, 83}};
for (int i = 0; i < testScores.length; i++) {
int sum = 0;
for (int j = 0; j < testScores[i].length; j++) {
sum += testScores[i][j];
}
System.out.println("Average of Test#" + testScores[i]
+ "is " + sum / testScores[i].length);
System.out.println();
}
My final output should be something like:
Test#I has an average of J where I begins at 1 and goes to 4.
I will most likely need to add more tests later on as this develops, but I'm sure I will be able to manage that once I can get this sorted. I appreciate the assistance in advance!
You can iterate over the range
of row indices of this array, and for each row, put together in one entry
the incremented index of the row and its average
value. Your code might look something like this:
int[][] testScores = {
{100, 85, 91, 75, 82},
{81, 75, 68, 92, 87},
{99, 71, 75, 84, 91},
{97, 91, 68, 72, 83}};
IntStream.range(0, testScores.length)
// Stream<Map.Entry<Integer,Double>>
.mapToObj(i -> Map.entry(
// number of the line of scores
i + 1,
// average value for this line
Arrays.stream(testScores[i])
.average().orElse(0)))
// output
.forEach(System.out::println);
1=86.6
2=80.6
3=84.0
4=82.2