我的程序在没有编译错误的意义上正常工作。一旦我浏览了数据并输入了一些测试数据,例如名字:Bob,姓:Jones,课程:IT,等级:44。首先,它将它存储在" Grades.txt"文件。但是,当我重新运行程序时,文件会重置并且它是空的。为什么是这样?就好像数据只是临时存储在文件中一样。感谢
代码:
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.Scanner;
public class ExamGrades {
public static void main(String[] args) throws Exception {
FileWriter grades = new FileWriter("grades.txt");
BufferedWriter bw = new BufferedWriter(grades);
PrintWriter out = new PrintWriter(bw);
Scanner scan = new Scanner(System.in);
int examMark =0;
String firstName = "";
String surName = "";
String course = "";
System.out.print("Please enter student firstname: ");
firstName = scan.next();
System.out.print("Please enter student surname: ");
surName = scan.next();
System.out.print("Please select student course: ");
course = scan.next(); // Drop Down menu in future?
System.out.print("Please enter student mark: ");
while (!scan.hasNextInt())
{
System.out.print("Please enter a valid mark: ");
scan.next();
}
examMark = scan.nextInt();
if (examMark < 40)
{
System.out.println("Failed");
}
else if (examMark >= 40 && examMark <= 49)
{
System.out.println("3rd");
}
else if (examMark >= 50 && examMark <= 59)
{
System.out.println("2/2");
}
else if (examMark >= 60 && examMark <= 69)
{
System.out.println("2/1");
}
else if (examMark >= 70 && examMark <= 100)
{
System.out.println("1st");
}
else
{
System.out.println("Invalid Mark"); // If not within previous criteria, this prints
}
out.print(firstName + " ");
out.print(surName + ", ");
out.print(course + ", ");
out.print(examMark);
out.close();
scan.close();
}
}
答案 0 :(得分:2)
您需要将true作为第二个参数传递给FileWriter构造函数。
FileWriter构造函数接受的第二个参数名为&#34; append&#34;并确保FileWriter附加到文件而不是覆盖它。
例如:
FileWriter grades = new FileWriter("grades.txt", true);