/* CSE 142, Autumn 2007 (Marty Stepp) This program searches a file of employees for a particular person and prints information about that employee's hours worked. Example of input data: 123 Susan 12.5 8.1 7.6 3.2 456 Brad 4.0 11.6 6.5 2.7 12 Two example outputs: Enter a name: Brad Brad (ID#456) worked 36.8 hours (7.359999999999999 hours/day) Enter a name: Harvey Harvey was not found. */ import java.io.*; import java.util.*; public class Hours { public static void main(String[] args) throws FileNotFoundException { Scanner console = new Scanner(System.in); System.out.print("Enter a name: "); String name = console.next(); // e.g. "Brad" Scanner input = new Scanner(new File("hours.txt")); // "boolean flag" (5.2) // This variable remembers if we ever found the name or not. boolean found = false; while (input.hasNextLine() && !found) { String line = input.nextLine(); Scanner lineScan = new Scanner(line); if (processLine(lineScan, name)) { // We found the name! Remember this. found = true; } } if (found == false) { // didn't ever see the person; print an error message System.out.println(name + " was not found."); } } // This message examines a line of input and prints hours stats on it, // if the line is about the person represented by nameToLookFor. // The method returns true if the nameToLookFor was found and false if not. public static boolean processLine(Scanner lineScan, String nameToLookFor) { // read worker ID, name, total hours, # days int id = lineScan.nextInt(); String name = lineScan.next(); if (name.equals(nameToLookFor)) { // only print the output if this is the name they are looking for double totalHours = 0.0; int days = 0; while (lineScan.hasNextDouble()) { double hours = lineScan.nextDouble(); totalHours += hours; days++; } System.out.println(name + " (ID#" + id + ") worked " + totalHours + " hours (" + (totalHours / days) + " hours/day)"); return true; } else { // didn't find them return false; } } }