【问题标题】:Java Array save input to txt fileJava Array 将输入保存到 txt 文件
【发布时间】:2015-01-28 19:39:49
【问题描述】:

我已创建此代码以将学生信息保存到 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);
  • @Andrey 这是正确的答案。也许您可以将其写为答案,而不是评论;这样我就可以投票了,安娜可以接受。
  • 我并不是要更改您的代码,我只是重新格式化它以便于阅读。我删除了 import 语句,因为它们并不重要(它们对于运行代码很重要,但不是为了向我们展示代码:)

标签: java file arraylist


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    你必须添加这样的东西:

    Students.add(String.format("%s %s, id: %s, course: %s", studentName, studentSName, idstudent, course));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-07-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多