我在试着做一个给学生打分的程序。
首先,它应该询问学生的id,然后你需要将每个标准都给同一个学生。
在我给出分数后,这段代码不会改变任何东西。
BufferedReader br = new BufferedReader(new FileReader("project.csv"));
while ((line = br.readLine()) != null) {
String[] cols = line.split(",");
System.out.println("Please choose a criteria (2-7) ?");
int subjectToGiveMark = in .nextInt(); // for creativity is 2
System.out.println("Please enter a mark :");
int mark = in .nextInt(); // which mark should be given
final int size = cols.length;
String[] finalResult = new String[size];
int index = 0;
while (index < finalResult.length) {
if (index == subjectToGiveMark) {
finalResult[index] = mark + "";
} else {
finalResult[index] = cols[index];
}
index++;
}
}有人能告诉我它出了什么问题吗?enter image description here
发布于 2020-04-27 17:15:50
首先,为了安全起见,你应该使用try with resources来读写你的文件,因为你可能会忘记关闭文件,甚至一个异常也会阻止你这样做。
try-with-resources语句可确保在语句结束时关闭每个资源。
- Java™教程
更多信息:https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html
多么?例如,在你正在阅读的内容中,只要尝试一下就可以了:
try (BufferedReader br = new BufferedReader(new FileReader("project.csv"))) {
// The while code here...
}您还修改了finalResult变量,但没有对它做任何操作,所以您的更改只是存储在那里,没有其他内容,这就是为什么您看不到更改的原因!
您应该在while循环之外创建一个变量,存储所有行,就像一个列表。否则,您可以打开另一个文件(例如: project-output.csv),并在读取另一个文件的同时写入该文件。
// Same principle as reading
try (BufferedWriter writer = new BufferedWriter(new FileWriter("project.csv"))) {
// Write the result
}这个答案更详细地解决了写作的主题:https://stackoverflow.com/a/2885224/1842548
读写的例子,我假设是Java 8:
try (BufferedWriter writer = new BufferedWriter(new FileWriter("project-output.csv"))) {
try (BufferedReader reader = new BufferedReader(new FileReader("project.csv"))) {
String line;
while ((line = reader.readLine()) != null) {
String[] cols = line.split(",");
System.out.println("Please choose a criteria (2-7): ");
final int subjectToGiveMark = in.nextInt(); // for creativity is 2
System.out.println("Please enter a mark: ");
final int mark = in.nextInt(); // which mark should be given
cols[subjectToGiveMark] = Integer.toString(mark);
// Here is where you write the output:
writer.write(String.join(",", cols));
writer.newLine();
}
writer.flush();
}
}您可以在repl.it https://repl.it/repls/ScaredSeriousCookie上查看工作示例
https://stackoverflow.com/questions/61445355
复制相似问题