DeansList.java
Download DeansList.java
1: // DeansList.java - A program to read in a bunch of student records
2: // from a file, and print all student names who have a GPA greater than
3: // 3.0 (the cut-off for making the Dean's list). The file format is:
4: // count_of_records (int) <newline>
5: // name (String) <tab> GPA (double) <newline>
6: //
7: // The file name is passed as a command line argument to the program.
8: //
9: // Storing the data in a collection is NOT required in this case,
10: // since the data only needs to be processed once. Compare this with the
11: // program AverageGPA.java.
12: //
13: // Written 2018 Wayne Pollock, Tampa FL USA.
14:
15: import java.nio.file.Paths;
16: import java.util.*;
17:
18: public class DeansList {
19: final static double DEANS_LIST_MINIMUM__GPA = 3.00;
20:
21: public static void main ( String [] args ) {
22: Scanner in;
23:
24: // Filename should be a file in (or relative to) the current directory:
25: if ( args.length != 1 ) {
26: System.out.println( "\nUsage: java DeansList <name_of_datafile>"
27: + "\n(example: java DeansList StudentRecords.txt)" );
28: return;
29: }
30:
31: try { // Make a Scanner from the filename:
32: in = new Scanner( Paths.get(args[0]) );
33: in.nextLine(); // Throw away the count of records line.
34: // Use tabs and newlines as field delimiters for rest of file:
35: in.useDelimiter( "[\\t\\r\\n]" );
36: }
37: catch ( Exception e ) {
38: System.err.println( "\n*** Could not read number of records from file"
39: + " (the first line).\n" + e.toString() );
40: return;
41: }
42:
43: // Display a title for the output list:
44: System.out.printf(
45: "%n Students on Dean's List (GPA greater than %.2f):%n%n",
46: DEANS_LIST_MINIMUM__GPA );
47:
48: boolean atLeastOne = false;
49: while ( in.hasNextLine() ) {
50: try {
51: String name = in.next(); // Read up to a tab
52: double GPA = in.nextDouble();
53: in.nextLine(); // Skip over the newline
54:
55: if ( GPA > DEANS_LIST_MINIMUM__GPA ) {
56: System.out.printf( "\t%-18s (%.2f)%n", name, GPA );
57: atLeastOne = true;
58: }
59: }
60: catch ( InputMismatchException ime ) {
61: System.err.println( "Error: Badly formatted input data" );
62: return; // TODO probably should continue, to just skip bad data.
63: }
64: }
65:
66: if ( ! atLeastOne ) {
67: System.out.println(" (No students made the Dean's list this time.)");
68: }
69: }
70: }