// This program searches an input file of employees' hours worked // for a particular employee and outputs that employee's hours data. // // Second version that uses a method and demonstrates the use of null. import java.io.*; // for File import java.util.*; // for Scanner public class HoursWorked2 { public static void main(String[] args) throws FileNotFoundException { Scanner console = new Scanner(System.in); System.out.print("Enter a name: "); String searchName = console.next(); // "BRAD" Scanner input = new Scanner(new File("hours.txt")); Scanner lineScan = search(input, searchName); if (lineScan == null) { System.out.println("Not found!"); } else { // process the line double sum = 0.0; int count = 0; while (lineScan.hasNextDouble()) { double hours = lineScan.nextDouble(); sum += hours; count++; } double average = sum / count; System.out.println(searchName + " worked " + sum + " hours (" + average + " hours/day)"); } } // Searches the input file for the record of the person with the given // name. Returns the line containing this record, or null if not found. public static Scanner search(Scanner input, String searchName) { while (input.hasNextLine()) { String line = input.nextLine(); // "456 Brad 4.0 11.6 6.5 2.7 12" Scanner lineScan = new Scanner(line); int id = lineScan.nextInt(); // 456 String name = lineScan.next(); // "Brad" if (name.equalsIgnoreCase(searchName)) { return lineScan; } } return null; // not found } }