Advertisement
Guest User

t4

a guest
Mar 18th, 2019
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.86 KB | None | 0 0
  1. import java.io.File;
  2. import java.io.IOException;
  3. import java.io.PrintWriter;
  4. import java.util.*;
  5.  
  6. public class HW01_4 {
  7. public static void main(String[] args) {
  8. File f = new File("results.csv");
  9. File tsv = new File("results.tsv");
  10. Scanner sc = null;
  11. PrintWriter pw = null;
  12. try {
  13. sc = new Scanner(f);
  14. pw = new PrintWriter(tsv);
  15. if(!sc.hasNext()) {
  16. System.out.println("The file is empty");
  17. return;
  18. }
  19. Map<Integer, String> subjectByIndex = new HashMap<>();
  20. Map<String, List<Integer>> subjects = new LinkedHashMap<>();
  21. Map<String, List<Integer>> students = new LinkedHashMap<>();
  22.  
  23. String line = sc.nextLine();
  24. pw.write(line.replace(",", "\t") + "\n");
  25. String[] lines = line.split(",");
  26.  
  27. for (int i = 1; i < lines.length; i++) {
  28. subjectByIndex.put(i,lines[i]);
  29. subjects.put(lines[i],new ArrayList<>());
  30. }
  31.  
  32. while(true) {
  33. line = sc.nextLine();
  34. lines = line.split(",");
  35. String studentIndex = lines[0];
  36. students.put(studentIndex,new ArrayList<>());
  37.  
  38. for (int i = 1; i < lines.length; i++) {
  39. int grade = Integer.parseInt(lines[i]);
  40. students.get(studentIndex).add(grade);
  41. String subject = subjectByIndex.get(i);
  42. subjects.get(subject).add(grade);
  43. }
  44. if(sc.hasNext())
  45. pw.write(line.replace(",", "\t") + "\n");
  46. else {
  47. pw.write(line.replace(",", "\t"));
  48. break;
  49. }
  50. }
  51. subjects.keySet().stream()
  52. .forEach(key -> {
  53. double avg = subjects.get(key)
  54. .stream()
  55. .mapToInt(i -> i)
  56. .average()
  57. .getAsDouble();
  58. System.out.println("Average grade of " + key + " is " + avg);
  59. });
  60. students.keySet().stream()
  61. .forEach(key -> {
  62. double avg = students.get(key)
  63. .stream()
  64. .mapToInt(i -> i)
  65. .average()
  66. .getAsDouble();
  67. System.out.println("Average grade of student with index " + key + " is " + avg);
  68. });
  69.  
  70.  
  71. }
  72. catch (IOException e) {
  73. e.printStackTrace();
  74. }
  75. finally {
  76. sc.close();
  77. pw.close();
  78. }
  79. }
  80. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement