public class StreamNumberExceptionSolution
1: //StreamNumberExceptionSolution.java
3: import java.util.Scanner;
5: public class StreamNumberExceptionSolution
6: {
8: public static void main(String [] args)
9: {
10: // Describe the format of a row of input. There are four fields in a
11: // row, separated by commas: last name, first name, department, salary
12: final String SEPARATOR = ","; // Field separator in each row of data
13: final int INDEX_LAST_NAME = 0; // # of the last name field
14: final int INDEX_FIRST_NAME = 1; // # of the first name field
15: final int INDEX_DEPT = 2; // # of the department name field
16: final int INDEX_SALARY = 3; // # of the salary field
17: Scanner scnr = new Scanner(System.in);
19: String [] field; // Fields on one row in the input file
20: String row; // One row of the input file
21: int nRows; // Counts # of rows in the input file
22: int totalSalaries; // Total of all salaries read
24: nRows = 0;
25: totalSalaries = 0;
27: while (scnr.hasNext()) // Loop while input data exists
28: {
29: row = scnr.nextLine();
30: ++nRows;
31: System.out.println(nRows + ") " + row);
32: field = row.split(SEPARATOR);
34: try // Ensure an integer was input
35: {
36: totalSalaries += Integer.parseInt(field[INDEX_SALARY]);
37: System.out.println
38: (
39: " "
40: + field[INDEX_FIRST_NAME] + SEPARATOR
41: + field[INDEX_LAST_NAME] + SEPARATOR
42: + field[INDEX_SALARY ] + SEPARATOR
43: + field[INDEX_DEPT]
44: );
45: }
46: catch (NumberFormatException e)
47: {
48: System.out.println
49: (
50: "The salary entry for "
51: + field[INDEX_FIRST_NAME] + " "
52: + field[INDEX_LAST_NAME]
53: + ", "
54: + field[INDEX_SALARY]
55: + ", is not an integer.\n"
56: + "This info won't be added to the salary running total.\n"
57: );
58: }
59: }
61: System.out.println();
62: System.out.printf("Total salaries: $%,8d", totalSalaries);
63: }
64: }