Tuesday 1 October 2013

TextIO program not giving the desired output

TextIO program not giving the desired output

OK, time to give the noob a hard time. I am writing a program that is
supposed to use an algorithm to write all even integers from 1 to 100 to a
file, close the file, then display the results. Then id is supposed to
append the file with all of the odd integers from 1 to 100, close the
file, reopen and display the results. Something like: 1st list - 2, 4, 6,
8, ......., 98, 100 2nd list - 2, 4, 6, 8, ......., 98, 100, 1 , 3, 5,
...., 97, 99
I get the even(1st) list fine. The 2nd list displays just the odd numbers.
Sure it is something simple, usually is. My brain is mush right now and I
am not seeing it. Thanks for any help!!
package textFileIO;
import java.io.*;
public class TextFileIO {
public static void main(String[] args) throws Exception {
//Create newFile
File newFile = new File("numbers.dat");
newFile.createNewFile();
int evenNum = 0;
int oddNum = 0;
try{
BufferedWriter writer = new BufferedWriter(new FileWriter(newFile));
//Loop from 1 to 100
for (int i = 2; i <= 100; i+=2)
{
evenNum += i + 1;
writer.write("" + i + ", ");
}
writer.newLine();
writer.close();
BufferedReader reader = new BufferedReader(new FileReader(newFile));
System.out.println(reader.readLine());
reader.close();
BufferedWriter writer2 = new BufferedWriter(new FileWriter(newFile));
for(int i = 1; i < 100; i +=2) {
oddNum += i;
writer2.write("" + i + ", ");
}
writer2.newLine();
writer2.close();
BufferedReader reader2 = new BufferedReader(new FileReader(newFile));
System.out.printf(reader2.readLine());
}
catch (Exception e){
}
}
}

No comments:

Post a Comment