这是我代码的一部分。基本上,我试图将double Avg和char gradeLetter中的值存储在doubleAVG和charGRADE数组中。到目前为止,我得到的是在第一个循环中,假设Avg = 2,那么它将被存储在文件中,但是如果存在第二个循环,并且Avg的值更改为3,那么3将被保存在文件中两次。它将删除2并将数字3保存两次。我该如何解决?我希望第一个循环存储可以设置为2的Avg的第一个值,然后在第二个循环中存储可以设置为3的平均Avg的新值,但不覆盖2。忽略注释。
try {
FileWriter fw = new FileWriter(fileN);
for (int count = 0; count < students; count++) {
doubleAVG = new double[students];
charGRADE = new char[students];
doubleAVG[count] = Avg;
charGRADE[count] = gradeLetter;
fw.write("This is the grade of: " + FirstName + " " + LastName
+ " ");
fw.write(String.valueOf(doubleAVG[count]) + " ");
fw.write(charGRADE[count]);
}
fw.close();
} catch (Exception e) {
System.out.println(e);
}
答案 0 :(得分:0)
请为此修改您的代码:
public class Main {
public static void main(String[] args) {
try {
FileWriter fw = new FileWriter(new File("F://test.txt"));
Scanner sc = new Scanner(System.in);
int students = 2;
double[] doubleAVG = new double[students];
char[] charGRADE = new char[students];
double avg = 0.0;
char gradeLetter;
String FirstName = "";
String LastName = "";
for (int count = 0; count < students; count++) {
System.out.println("Enter average :");
avg = sc.nextDouble();
System.out.println("Enter grade :");
gradeLetter = sc.next().charAt(0);
System.out.println("Enter First Name :");
FirstName = sc.next();
System.out.println("Enter Last Name :");
LastName = sc.next();
doubleAVG[count] = avg;
charGRADE[count] = gradeLetter;
fw.write("This is the grade of: " + FirstName + " " + LastName + " ");
fw.write(String.valueOf(doubleAVG[count]) + " ");
fw.write(charGRADE[count] + System.lineSeparator());
}
fw.close();
sc.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
控制台输入:
Enter average :
70.45
Enter grade :
B
Enter First Name :
John
Enter Last Name :
Johnson
Enter average :
90.47
Enter grade :
A
Enter First Name :
Michael
Enter Last Name :
Jordan
在 test.txt 中:
This is the grade of: John Johnson 70.45 B
This is the grade of: Michael Jordan 90.47 A
答案 1 :(得分:-1)
您是否知道java Serialize方法,该方法将创建类文件及其对象中具有的所有数据结构的xml文件,使其中的嵌套结构看起来像特定时间点的对象一样原始XML?这可能是由于在5种确切的本机数据类型上中继了Java,而对象只是这些数据类型的集合。看看上面带有Stackoverflow答案链接的评论,我只是向您介绍了该机制。