好的,是时候让菜鸟难过了。我正在编写一个程序,该程序应该使用算法将所有从 1 到 100 的偶数写入文件,关闭文件,然后显示结果。然后 id 应该在文件中附加从 1 到 100 的所有奇数,关闭文件,重新打开并显示结果。类似于:第一个列表 - 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){
}
}
}