// Reads employee records and prints the information // about one employee. // This version correctly handles the "employee not found" case. 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 nameToSearchFor = console.next(); // "Brad" // a "boolean flag": have we found the name we're looking for yet? boolean found = false; Scanner input = new Scanner(new File("hours.txt")); while (input.hasNextLine()) { String line = input.nextLine(); // "123 Susan 12.5 8.1 7.6 3.2" // substring, indexOf, charAt, startsWith // the line contains the name Scanner lineScanner = new Scanner(line); // process one employee int id = lineScanner.nextInt(); String name = lineScanner.next(); if (name.equalsIgnoreCase(nameToSearchFor)) { found = true; // found them! double sum = 0.0; while (lineScanner.hasNextDouble()) { double hours = lineScanner.nextDouble(); sum += hours; } System.out.println(name + " worked " + sum + " hours."); } } // if found == true, we did find the person in the file // if found == false, we didn't // if (found == false) { if (!found) { System.out.println(nameToSearchFor + " was not found."); } } }