129k views
4 votes
3) Write a Java application that asks the user to enter the scores in 3 different tests (test1, test2, test3) for 5 students into a 2D array of doubles. The program should calculate the average score in the 3 tests for each student, as well as the average of all students for test1, test2 and test3.

1 Answer

6 votes

Answer:

import java.util.Scanner;

public class TestScores {

public static void main(String[] args) {

// create a 2D array of doubles to hold the test scores

double[][] scores = new double[5][3];

// use a Scanner to get input from the user

Scanner input = new Scanner(System.in);

// loop through each student and each test to get the scores

for (int i = 0; i < 5; i++) {

for (int j = 0; j < 3; j++) {

System.out.print("Enter score for student " + (i+1) + " on test " + (j+1) + ": ");

scores[i][j] = input.nextDouble();

}

}

// calculate the average score for each student and print it out

for (int i = 0; i < 5; i++) {

double totalScore = 0;

for (int j = 0; j < 3; j++) {

totalScore += scores[i][j];

}

double averageScore = totalScore / 3;

System.out.println("Average score for student " + (i+1) + ": " + averageScore);

}

// calculate the average score for each test and print it out

for (int j = 0; j < 3; j++) {

double totalScore = 0;

for (int i = 0; i < 5; i++) {

totalScore += scores[i][j];

}

double averageScore = totalScore / 5;

System.out.println("Average score for test " + (j+1) + ": " + averageScore);

}

}

}

Step-by-step explanation:

Here's how the program works:

It creates a 2D array of doubles with 5 rows (one for each student) and 3 columns (one for each test).

It uses a Scanner to get input from the user for each test score for each student. It prompts the user with the student number and test number for each score.

It loops through each student and calculates the average score for each student by adding up all the test scores for that student and dividing by 3 (the number of tests).

It prints out the average score for each student.

It loops through each test and calculates the average score for each test by adding up all the test scores for that test and dividing by 5 (the number of students).

It prints out the average score for each test.

Note that this program assumes that the user will input valid numbers for the test scores. If the user inputs non-numeric data or numbers outside the expected range, the program will throw an exception. To handle this, you could add input validation code to ensure that the user inputs valid data.

User Daremkd
by
8.0k points