gpt4 book ai didi

Java不会将所有内容写入文件

转载 作者:行者123 更新时间:2023-12-02 05:16:13 24 4
gpt4 key购买 nike

我正在尝试做一项作业,但我不明白为什么它不会将所有收集到的数据写入文本文件。基本上,我需要读取一个名为“marks”的 .txt 文件,将其输出(确实如此),然后将其分类为两个文件 - 如果成绩低于 50,它将转到fail.txt,如果成绩为 50 或更高它会将其放入 pass.txt 中。它只取出marks.txt中的第一个pass并将其放入pass.txt和marks.txt中的一个,我需要对所有8个进行排序。

来源如下:

import java.io.*;  

public class WriteKONG {
public static BufferedReader read;
public static PrintWriter WriteToPass;
public static PrintWriter WriteToFail;
public static String line;


public static void main(String[] args) throws IOException {
read = new BufferedReader(new FileReader("src/marks.txt"));
WriteToPass = new PrintWriter(new FileWriter("pass.txt"));
WriteToFail = new PrintWriter(new FileWriter("fail.txt"));
String StudentID;
String Course;
String MarkS;
int Mark;

line = read.readLine();

while(line != null)
{
sort();
}


}


public static void sort() throws IOException
{

read = new BufferedReader(new FileReader("src/marks.txt"));
WriteToPass = new PrintWriter(new FileWriter("pass.txt"));
WriteToFail = new PrintWriter(new FileWriter("fail.txt"));
String StudentID;
String Course;
String SMark;
int Mark;
while (line != null) {
line = read.readLine();
StudentID = line;
System.out.println("StudentID = " + StudentID);

line = read.readLine();
Course = line;
System.out.println("Course = " + Course);

line = read.readLine();
SMark = line;
System.out.println("Mark = " + SMark + "\n");

Mark = Integer.valueOf(SMark);
if(Mark >= 50)
{
WriteToPass.println(StudentID);
WriteToPass.println(Course);
WriteToPass.println(SMark);
WriteTopass.close();
}

else
{
WriteToFail.println(StudentID);
WriteToFail.println(Course);
WriteToFail.println(SMark);
WriteToFail.println(line);
WriteToFail.close();
}

}

}
}

这是marks.txt:

75676881
English
94
75676883
Math
78
75676885
Physics
24
75676887
Chemistry
89
75676889
English
35
75676891
History
24

最佳答案

您将在第一次迭代后关闭 WriteToFail,并且永远不会关闭 WriteToPass

您应该仅在循环之后关闭这两个文件:

line = read.readLine();
while (line != null) {
StudentID = line;
System.out.println("StudentID = " + StudentID);

line = read.readLine();
Course = line;
System.out.println("Course = " + Course);

line = read.readLine();
SMark = line;
System.out.println("Mark = " + SMark + "\n");

Mark = Integer.valueOf(SMark);
if(Mark >= 50)
{
WriteToPass.println(StudentID);
WriteToPass.println(Course);
WriteToPass.println(SMark);
}
else
{
WriteToFail.println(StudentID);
WriteToFail.println(Course);
WriteToFail.println(SMark);
WriteToFail.println(line);
}
line = read.readLine();
}
WriteToPass.close();
WriteToFail.close();

我刚刚注意到您在 main 方法和 sort 方法中打开文件。我认为没有理由这样做。你的 main 应该只调用 sort :

public static void main(String[] args) throws IOException  
{
sort();
}

关于Java不会将所有内容写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26936707/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com