Try/catch & 在 Java 中使用 Scanner 保存 ArrayList

Try/catch & saving an ArrayList using Scanner in Java

我不知道如何正确编码。我已经阅读了整个互联网和我的书,也许我把它复杂化了。

我正在尝试将 arraylist 保存到 .txt - 显然,当我按“1”添加(studentInfo)时,它给了我异常,因为显然这是我告诉它做的。

我想要的是 add() ,如果文件存在则覆盖它或打开它并再次保存。

如果这听起来令人困惑,我深表歉意。我自己也很困惑。

case 1: 
                    try{
                    addStudent(studentInfo);
                    }
                    catch(FileNotFoundException ex){
                     ex.printStackTrace();
                     }
                    break;
                case 2: 
                    removeStudent(studentInfo);
                    break;
                case 3: 
                    display(studentInfo);
                    break;
                case 4:
                    load(studentInfo);
                case 0: 
                    System.out.println("Thank you for using the student database!");
                    System.exit(0);
            }
        }

   }  



    //ADD 
    private void addStudent(ArrayList<Student> studentInfo) throws FileNotFoundException  { 


         Scanner add = new Scanner(new File("students.txt"));

         while(add.hasNext()){    

         System.out.println("\nEnter the student's name: ");
         String name = add.nextLine();

         System.out.println("\nEnter the student's last name: ");
         String lastName = add.nextLine();

         System.out.println("\nEnter the student's major: ");
         String major = add.nextLine();

         System.out.println("\nEnter the student's GPA: ");
         String gpaNumber = add.nextLine();
         double gpa  = Double.parseDouble(gpaNumber);

         System.out.println("\nEnter the student's UIN: ");
         String uinNumber = add.nextLine();
         int uin = Integer.parseInt(uinNumber);

         System.out.println("\nEnter the student's NetID: ");
         String idName = add.nextLine();

         System.out.println("\nEnter the student's age: ");
         String years = add.nextLine();
         int age = Integer.parseInt(years);

         System.out.println("\nEnter the student's gender: Female or Male ");
         String gender = add.nextLine();

         Student newStudent = new Student (name, lastName, major, gpa, uin, idName, age, gender);

         if(studentInfo.size() <10){
         studentInfo.add(newStudent);
         System.out.println("Student information saved.");
         System.out.println();
         }
         else{
            System.out.println("Database is full");
         }

         }

         add.close();


   }

我的理解是,你正在尝试构造一个新的学生对象,输入一个学生的信息,然后将所有学生的信息写入一个文件。

new File(students.txt) 是您告诉 Java 如何使用现有文件的方式,它无法创建文件,这就是导致错误的原因。如果您想查看错误解决后代码的执行情况,您可以创建一个 students.txt 文件。

Scanner 是输入处理程序,而不是文档编写器。因此,当您的 add Scanner 是使用 File 对象构造的时,它实际上将读取该文件中已经存在的信息。它不允许您写入文件。

此外,当您使用 nextLine() 时,它会遍历文件中的行,而不是写入(或接受)您的输入。

我建议阅读 Java 文件 I/O。网上和 Stack Overflow 上有很多资料。如果这是一项家庭作业,请注意不要使用任何内容 "cutting edge" 如果您的老师希望您照章办事。