/** 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 Driver { public static void main(String [] args) throws IOException { BufferedReader in = null; try { in = new BufferedReader(new FileReader("menu.txt")); } catch (FileNotFoundException e) { System.out.println("Sorry, can't find menu file."); System.exit(1); } // 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, " "); // The price is the 2nd token, so skip first token. try { tok.nextToken(); sumPrices += Double.parseDouble(tok.nextToken()); ++numItems; } // If the line of text is not of the form [item, price], skip it. catch (NoSuchElementException e) { continue; } // If there's a number format exception, also skip. catch (NumberFormatException e) { continue; } } in.close(); double average = sumPrices / numItems; System.out.printf("Average menu item price is $ %.2f\n", average); } }