Exercise 2. You will create a file where each line represents a student (their f
ID: 3700479 • Letter: E
Question
Exercise 2. You will create a file where each line represents a student (their first name and last name) and four lab marks (all integers out of 10). You need to read the lines from this file using a Scanner object and then reformat the data and write the data using a PrintWriter object (students last name, first name with their average lab mark) in a new file. At the bottom of the new file also print the number of students and the average lab mark for the entire class. Below, you can see the unformatted text in Students.txt and the formatted text in Formatted.txt.- Students.txt (before formatting Lorri Black 10 9 7 6+ Jim Liam 10 9 9 8+ Clem Pint 7 6 8 7 Steve Clark 3 7 9 0 Sara Term 8 10 9 10 Pete Song 9 9 8 7 Formatted.txt (after forma Name Ave Lab Markt Black, Lorri 8.0 Liam, Jim Pint, Clem 7.0+ Clark, Steve 4.75+ Term, Sara 9.25+ Song, Pete 8.25 9.0 Total Students: 6 Average lab class: 7.5Explanation / Answer
import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.Scanner; public class StudentAverages { public static void main(String[] args) { try { Scanner fin = new Scanner(new File("Students.txt")); PrintWriter pw = new PrintWriter("Formatted.txt"); double totalAvg = 0, count = 0, score; String fn, ln; pw.println(String.format("%20s Ave Lab Mark", "Name")); while(fin.hasNext()) { fn = fin.next(); ln = fin.next(); score = 0; score += fin.nextDouble(); score += fin.nextDouble(); score += fin.nextDouble(); score += fin.nextDouble(); score /= 4; totalAvg += score; count += 1; pw.println(String.format("%20s %.1f", ln+fn, score)); } pw.println(); pw.printf("Total Students: %d Average lab class: %.1f ", (int)count, totalAvg/count); pw.flush(); pw.close(); fin.close(); } catch (FileNotFoundException e) { System.out.println("Students.txt does not exists"); } } }
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.