java - How to store values in an array and save them in a file
问题描述
This is my part of my code. Basically I am trying to store the values from double Avg and char gradeLetter in the arrays doubleAVG and charGRADE. What im getting so far is that on the first loop, lets say Avg = 2 then that will be a stored in the file, but if there is a second loop and the value of Avg changes to 3 then 3 will be saved in the file twice. It deletes 2 and saves the number 3 twice. How can i fix that? I want the first loop to store the first value of Avg that can be 2 and then on the second loop to store the new value of Avg that could be 3 but without overwriting the 2. IGNORE THE COMMENTS.
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);
}
解决方案
请将您的代码修改为:
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
推荐阅读
- spring-webflux - 项目反应堆。Mono.map() 与 Mono.flatMap()
- processing - 我的球移动不顺畅,但有口吃。如何实现更流畅的运动?
- apache-spark - 来自databricks的apache.avro和spark-avro之间的区别
- sql - 在 SSIS 中使用 case 语句
- r - 随机森林模型的输出值是否可以接受?
- azure-cognitive-services - southasia.api.cognitive.microsoft.com 无法正常工作
- java - 无法将附件添加到新的 RT 票证
- react-native - 在文本组件中嵌套视图组件不起作用 react-native 0.60-RC
- bash - 从 Bash 中的变量列表中获取字符串
- python - 使用 IAM 用户身份验证连接到 Aurora MySQL 的 Python 示例