Share on Google+Share on Google+

Calculate sum of even and odd numbers in Java

Advertisement
In this Java Tutorial session, you will learn how to read the file that contains even and odd numbers and calculate their sum separately.

Calculate sum of even and odd numbers

In this section, you will learn how to read the file that contains even and odd numbers and calculate their sum separately. To do this, first of all, we have found all the even and odd numbers from 1 to 100.Then we have created a file and add even and odd numbered integers separated by a comma to it. After that we have used StreamTokenizer class to parse numbers from the file and then calculate their sum.

Here is the code:

import java.io.*;

class AddEvenAndOdd {
	public static void main(String[] args) throws Exception {
		String evenNo = "";
		String oddNo = "";
		for (int i = 1; i < 100; i++) {
			if (i % 2 == 0) {
				evenNo += i + ",";
			} else {
				oddNo += i + ",";
			}
		}
		File myFile = new File("numbers.txt");
		FileWriter outStream = new FileWriter(myFile, true);
		BufferedWriter out = new BufferedWriter(outStream);
		out.write(evenNo);
		out.write("\n");
		out.close();
		Reader r = new BufferedReader(new FileReader(myFile));
		StreamTokenizer st = new StreamTokenizer(r);
		st.parseNumbers();
		int sum1 = 0;
		st.nextToken();
		while (st.ttype != StreamTokenizer.TT_EOF) {
			if (st.ttype == StreamTokenizer.TT_NUMBER)
				sum1 += st.nval;
			else
				System.out.print("");
			st.nextToken();
		}
		System.out.println("Sum of even numbers is: " + sum1);
		FileWriter outStream1 = new FileWriter(myFile, true);
		BufferedWriter out1 = new BufferedWriter(outStream1);
		out1.write(oddNo);
		out1.close();

		Reader reader = new BufferedReader(new FileReader(myFile));
		StreamTokenizer stt = new StreamTokenizer(reader);
		int sum = 0;
		stt.parseNumbers();
		stt.nextToken();
		while (stt.ttype != StreamTokenizer.TT_EOF) {
			if (stt.ttype == StreamTokenizer.TT_NUMBER)
				sum += stt.nval;
			else
				System.out.print("");
			stt.nextToken();
		}
		int sum2 = sum - sum1;
		System.out.println("Sum of odd numbers is: " + sum2);
	}
}

Output

Sum of even numbers is: 2450
Sum of odd numbers is: 2500

Advertisements

Advertisement

Posted on: November 10, 2009 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.