/* Marty Stepp, CSE 142, Spring 2010 This program reads an input file of TAs' hours worked and outputs each TA's total hours for the week and hours per day. Input file hours.txt: 123 Kim 12.5 8.1 7.6 3.2 456 Eric 4.0 11.6 6.5 2.7 12 1.5 2.6 789 Stef 8.0 8.0 8.0 8.0 7.5 Expected output (to console): Kim (ID#123) worked 31.4 hours (7.85 hours/day) Eric (ID#456) worked 36.8 hours (7.36 hours/day) Stef (ID#789) worked 39.5 hours (7.9 hours/day) */ // This program searches an input file of employees' hours worked // for a particular employee and outputs that employee's hours data. import java.io.*; // for File import java.util.*; // for Scanner public class HoursWorked { public static void main(String[] args) throws FileNotFoundException { Scanner console = new Scanner(System.in); System.out.print("Enter an ID: "); int searchId = console.nextInt(); // e.g. 456 Scanner input = new Scanner(new File("hours.txt")); String line = findPerson(input, searchId); if (line.length() > 0) { processLine(line); } else { System.out.println("ID #" + searchId + " was not found"); } } // Locates and returns the line of data about a particular person. public static String findPerson(Scanner input, int searchId) { while (input.hasNextLine()) { String line = input.nextLine(); Scanner lineScan = new Scanner(line); int id = lineScan.nextInt(); // e.g. 456 if (id == searchId) { return line; // we found them! } } return ""; // not found, so return an empty line } // Totals the hours worked by the person and outputs their info. public static void processLine(String line) { Scanner lineScan = new Scanner(line); int id = lineScan.nextInt(); // e.g. 456 String name = lineScan.next(); // e.g. "Brad" double hours = 0.0; int days = 0; while (lineScan.hasNextDouble()) { hours += lineScan.nextDouble(); days++; } System.out.println(name + " worked " + hours + " hours (" + (hours / days) + " hours/day)"); } }