无法让程序正确编写和显示

时间:2013-10-02 01:34:03

标签: java

好的,是时候让菜鸟很难了。我正在编写一个程序,它应该使用算法将所有偶数从1到100的整数写入文件,关闭文件,然后显示结果。然后id应该附加1到100的所有奇数整数的文件,关闭文件,重新打开并显示结果。就像是: 第1列表 - 2,4,6,8,.......,98,100 第二个清单 - 2,4,6,8,......,98,100,1,3,5 ......,97,99

我得到了偶数(第一)名单。第二个列表只显示奇数。当然这很简单,通常是。我的大脑现在已经糊里糊涂了,我没有看到它。谢谢你的帮助!!

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, true)); 

    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){

   }
 }
}

1 个答案:

答案 0 :(得分:3)

writer2的声明更改为

BufferedWriter writer2 = new BufferedWriter(new FileWriter(newFile, true)); 

true将使编写者附加到现有文件,而不是覆盖它。