[英]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文件。
掃描程序是輸入處理程序,而不是文檔編寫器。 因此,當您使用文件對象構造add
掃描程序時,它實際上將讀取該文件中已經存在的信息。 它不允許您寫入文件。
此外,當您使用nextLine()
,它將遍歷文件中的行,而不是寫入(或接受)您的輸入。
我建議閱讀Java File I / O。 在線上有很多材料,此處有Stack Overflow。 如果這是一項家庭作業,請注意,如果您的老師希望您遵守本書,不要使用任何“尖端技術”。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.