/* Program that reads integer values from a file and adds them up. * * Carsten Butz, October 2002 */ import java.io.*; import java.util.StringTokenizer; class AddNumbers{ public static void main(String[] args) throws IOException { /* Print an error message if no file name is given and exit. */ if(args.length ==0){ System.out.println("Usage: java AddNumbers filename"); System.exit(0); } /* Start the 'real' program. */ int sum = 0; String line = null; /* Open the file for reading. */ BufferedReader input = new BufferedReader(new FileReader(args[0])); /* Read the first line. */ line = input.readLine(); /* For non-empty lines do the following: */ while(line != null){ System.out.println(line); // print out line as a check /* Create a new String Tokenizer. Tokens a separated by spaces. */ StringTokenizer st = new StringTokenizer(line, " "); /* The following loop splits the StringTokenizer into individual tokens * (while they are available), and tries to parse an integer value from * each individual token. If this fails an error message is printed. */ while(st.hasMoreTokens()){ try{ sum = sum + Integer.parseInt(st.nextToken()); } catch(NumberFormatException nfe) { System.out.println("The file contained a non-integer value!"); } } /* The line is handled and we can read the next line. */ line = input.readLine(); } System.out.println("The sum is " + sum + "."); } }