/** Let's experiment with some exception handling in Java * Read a menu, and find the average price of the items. */ import java.io.*; import java.util.*; public class ReadMenu { public static void main(String [] args) throws IOException { BufferedReader in = new BufferedReader(new FileReader("menu.txt")); // Read lines of text from the menu file. Each line contains an item // and a price. Keep track of sum so we can figure the average. double sumPrices = 0.0; int numItems = 0; while(true) { String line = in.readLine(); if (line == null) break; // Let's assume we can separate the tokens by a space. // Later, to make the program more robust, we can handle menu items // that are more than one word. StringTokenizer tok = new StringTokenizer(line, " "); tok.nextToken(); sumPrices += Double.parseDouble(tok.nextToken()); ++numItems; } in.close(); double average = sumPrices / numItems; System.out.printf("Average menu item price is $ %.2f\n", average); } }