// CSE 142, Summer 2008 (Marty Stepp) // This program processes a file of employee data and outputs // each employee's hours worked and hours per day. // // The program demonstrates line-based file processing and using // a Scanner to tokenize the contents of each individual line. // // This second version demonstrates file searching. // It asks the user for an ID and only shows employee(s) that match it. import java.io.*; // File import java.util.*; // Scanner public class Hours2 { public static void main(String[] args) throws FileNotFoundException { Scanner console = new Scanner(System.in); System.out.print("Enter an ID: "); int desiredID = console.nextInt(); Scanner input = new Scanner(new File("hours.txt")); boolean found = false; // boolean flag; set to true if we find a match while (input.hasNextLine() && !found) { // "123 Susan 12.5 8.1 7.6 3.2" String line = input.nextLine(); Scanner lineScanner = new Scanner(line); int id = lineScanner.nextInt(); // 123 if (id == desiredID) { found = true; String name = lineScanner.next(); // "Susan" // cumulative sum of all hours worked by this employee double sum = 0.0; int days = 0; while (lineScanner.hasNextDouble()) { sum = sum + lineScanner.nextDouble(); days++; } System.out.println(name + " (ID#" + id + ") worked " + sum + " hours (" + (sum/days) + " / day)"); } } if (!found) { // never found a match; print error message System.out.println("ID#" + desiredID + " not found."); } } }