CSE142 Program Example handout #18 Input file hours.txt -------------------- 8 8 8 8 8 8 4 8 4 8 4 4 8 4 8 4 8 3 0 0 8 6 4 4 8 8 0 0 8 8 8 8 4 8 4 Program Output -------------- Total hours = 40 Total hours = 40 Total hours = 32 Total hours = 25 Total hours = 16 Total hours = 16 Total hours = 32 Mon hours = 43 Tue hours = 32 Wed hours = 36 Thu hours = 40 Fri hours = 34 Sat hours = 8 Sun hours = 8 Total hours = 201 Program file Hours.java ----------------------- // Stuart Reges // 2/16/05 // This program reads an input file with information about hours worked and // produces a list of total hours worked each week and total hours worked for // each day of the week. Each line of the input file should contain // information for one week and should have up to 7 integers representing how // many hours were worked each day (Monday first, then Tuesday, through // Sunday). import java.io.*; public class Hours { public static final int DAYS = 7; // # of days in a week public static void main(String[] args) throws FileNotFoundException { Scanner input = new Scanner(new File("hours.txt")); processFile(input); } // processes an input file of data about hours worked by an employee public static void processFile(Scanner input) { int[] total = new int[DAYS]; while (input.hasNextLine()) { String text = input.nextLine(); Scanner data = new Scanner(text); int[] next = transferFrom(data); System.out.println("Total hours = " + sum(next)); addTo(total, next); } System.out.println(); print(total); } // constructs an array of DAYS integers initialized to 0 and transfers // data from the given Scanner into the array in order; assumes the // Scanner has no more than DAYS integers public static int[] transferFrom(Scanner data) { int[] result = new int[DAYS]; int i = 0; while (data.hasNextInt()) { result[i] = data.nextInt(); i++; } return result; } // returns the sum of the integers in the given array public static int sum(int[] numbers) { int sum = 0; for (int i = 0; i < numbers.length; i++) sum += numbers[i]; return sum; } // adds the values in next to their corresponding entries in total public static void addTo(int[] total, int[] next) { for (int i = 0; i < DAYS; i++) total[i] += next[i]; } // prints information about the totals including total hours for each // day of the week and total hours overall public static void print(int[] total) { String[] dayNames = {"Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"}; for (int i = 0; i < DAYS; i++) System.out.println(dayNames[i] + " hours = " + total[i]); System.out.println("Total hours = " + sum(total)); } }
Stuart Reges
Last modified: Wed Feb 16 10:32:04 PST 2005