gpt4 book ai didi

Java数组将输入保存到txt文件

转载 作者:行者123 更新时间:2023-12-01 18:22:40 24 4
gpt4 key购买 nike

我创建了此代码来将学生信息保存到 txt 文件,但它只保存名称。我找不到这有什么问题吗?我没有收到任何错误,程序运行得很好,期望一些错误处理和我必须添加的其他内容。

主类

public class Main {

public static void main(String[] args) throws IOException {
File fileName = new File("Students.txt");
ArrayList Students = new ArrayList();
String studentName = " ";
String studentSName = " ";
String idstudent = " ";
String course = " ";
while (!studentName.isEmpty()) {
studentName = JOptionPane.showInputDialog("Student's Name: ");
studentSName = JOptionPane.showInputDialog("Student's Surname: ");
idstudent = JOptionPane.showInputDialog("Student's IDnumber: ");
course = JOptionPane.showInputDialog("Student's Course: ");
if (!studentName.isEmpty()) {
Students.add(studentName);
}
}
try {
FileWriter fw = new FileWriter(fileName);
Writer output = new BufferedWriter(fw);
int sz = Students.size();
for (int i = 0; i < sz; i++) {
output.write(Students.get(i).toString() + "\n");
}
output.close();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "file not found");
}
}
}

二等:

public class filereading {

public static void main(String[] args) {
String FileName = "students.txt";
String line;
ArrayList Students = new ArrayList();

try {
BufferedReader input = new BufferedReader(new FileReader(FileName));
if (!input.ready()) {
throw new IOException();
}
while ((line = input.readLine()) != null) {
Students.add(line);
}
input.close();
} catch (IOException e) {
System.out.println(e);
}
int sz = Students.size();
for (int i = 0; i < sz; i++) {
System.out.println(Students.get(i).toString());

}
}
}

最佳答案

因为您只将名称添加到列表

 if (!studentName.isEmpty()) Students.add(studentName);

关于Java数组将输入保存到txt文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27217565/

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