Advertisement
Ligh7_of_H3av3n

05. Average Students Grades

May 20th, 2024
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.64 KB | None | 0 0
  1. package Lekciq;
  2.  
  3. import java.util.ArrayList;
  4. import java.util.Map;
  5. import java.util.Scanner;
  6. import java.util.TreeMap;
  7.  
  8. public class AverageStudentsGrades {
  9.     public static void main(String[] args) {
  10.         Scanner scanner = new Scanner(System.in);
  11.  
  12.  
  13.         int n = scanner.nextInt();
  14.         scanner.nextLine(); // Consume newline
  15.  
  16.         TreeMap<String, ArrayList<Double>> studentRecords = new TreeMap<>();
  17.  
  18.         // Reading input and populating student records
  19.         for (int i = 0; i < n; i++) {
  20.             String line = scanner.nextLine();
  21.             String[] parts = line.split(" ");
  22.             String name = parts[0];
  23.             double grade = Double.parseDouble(parts[1]);
  24.  
  25.             if (!studentRecords.containsKey(name)) {
  26.                 studentRecords.put(name, new ArrayList<>());
  27.             }
  28.             studentRecords.get(name).add(grade);
  29.         }
  30.  
  31.         // Printing grades and average grades for each student
  32.         for (Map.Entry<String, ArrayList<Double>> entry : studentRecords.entrySet()) {
  33.             String name = entry.getKey();
  34.             ArrayList<Double> grades = entry.getValue();
  35.             System.out.print(name + " -> ");
  36.             for (double grade : grades) {
  37.                 System.out.printf("%.2f ", grade);
  38.             }
  39.             System.out.printf("(avg: %.2f)\n", calculateAverage(grades));
  40.         }
  41.     }
  42.  
  43.     // Method to calculate the average grade
  44.     private static double calculateAverage(ArrayList<Double> grades) {
  45.         double sum = 0;
  46.         for (double grade : grades) {
  47.             sum += grade;
  48.         }
  49.         return sum / grades.size();
  50.     }
  51. }
  52.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement