/* filename: sum.java description: gets integers from file and sums the odd and even author: Kalin Ringkvist, k.rainquist@comcast.net version: 1.00 2004-01-30 */ //import the package so we can use the BufferedReader and util contains stringTokenizer import java.io.*; import java.util.*; import java.text.*; public class sum { public static void main(String[] args) throws IOException { /*declare variables and the BufferedReader class*/ BufferedReader inFile = new BufferedReader(new FileReader("numbers.txt")); String inputLine = inFile.readLine(); int number; int oddSum = 0; int evenSum = 0; //read line from file as a tokenizer string StringTokenizer tokenizer = new StringTokenizer(inputLine); /*Take integer from tokenizer, test for even or odd, and add to the appropriate type. Loop through all numbers*/ while(tokenizer.hasMoreTokens()) { number = Integer.parseInt(tokenizer.nextToken()); if(number % 2 == 0) evenSum = evenSum + number; else oddSum = oddSum + number; //check if you've reached end of tokens. if so, declare tokenizer as the next line in the file if(!tokenizer.hasMoreTokens()) { inputLine = inFile.readLine(); //enter next line from file if(inputLine == null) //if there is no line, break from "while" statement break; tokenizer = new StringTokenizer(inputLine); //tokenize next line in file } } //print results of the loop to the screen. System.out.println("The sum of the odds is: " + oddSum + ". And the sum of the evens is: " + evenSum + "."); } }