Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.File;
- import java.io.IOException;
- import java.io.PrintWriter;
- import java.util.*;
- public class HW01_4 {
- public static void main(String[] args) {
- File f = new File("results.csv");
- File tsv = new File("results.tsv");
- Scanner sc = null;
- PrintWriter pw = null;
- try {
- sc = new Scanner(f);
- pw = new PrintWriter(tsv);
- if(!sc.hasNext()) {
- System.out.println("The file is empty");
- return;
- }
- Map<Integer, String> subjectByIndex = new HashMap<>();
- Map<String, List<Integer>> subjects = new LinkedHashMap<>();
- Map<String, List<Integer>> students = new LinkedHashMap<>();
- String line = sc.nextLine();
- pw.write(line.replace(",", "\t") + "\n");
- String[] lines = line.split(",");
- for (int i = 1; i < lines.length; i++) {
- subjectByIndex.put(i,lines[i]);
- subjects.put(lines[i],new ArrayList<>());
- }
- while(true) {
- line = sc.nextLine();
- lines = line.split(",");
- String studentIndex = lines[0];
- students.put(studentIndex,new ArrayList<>());
- for (int i = 1; i < lines.length; i++) {
- int grade = Integer.parseInt(lines[i]);
- students.get(studentIndex).add(grade);
- String subject = subjectByIndex.get(i);
- subjects.get(subject).add(grade);
- }
- if(sc.hasNext())
- pw.write(line.replace(",", "\t") + "\n");
- else {
- pw.write(line.replace(",", "\t"));
- break;
- }
- }
- subjects.keySet().stream()
- .forEach(key -> {
- double avg = subjects.get(key)
- .stream()
- .mapToInt(i -> i)
- .average()
- .getAsDouble();
- System.out.println("Average grade of " + key + " is " + avg);
- });
- students.keySet().stream()
- .forEach(key -> {
- double avg = students.get(key)
- .stream()
- .mapToInt(i -> i)
- .average()
- .getAsDouble();
- System.out.println("Average grade of student with index " + key + " is " + avg);
- });
- }
- catch (IOException e) {
- e.printStackTrace();
- }
- finally {
- sc.close();
- pw.close();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement