【发布时间】:2016-08-31 02:31:22
【问题描述】:
public static ArrayList<Student> readStudentRecords(String fileName) throws FileNotFoundException {
Scanner input = new Scanner(new FileInputStream(fileName));
ArrayList<Student> students = new ArrayList<Student>();
input.useDelimiter(",");
String firstName, lastName, id, email, hashPW;
int maxCredits = 0;
while (input.hasNextLine()) {
try {
input.nextLine();
firstName = input.next();
lastName = input.next();
id = input.next();
email = input.next();
hashPW = input.next();
maxCredits = input.nextInt();
Student student = new Student(firstName, lastName, id, email, hashPW, maxCredits);
students.add(student);
} catch (IllegalArgumentException e) {
System.out.println("Illegal Argument Exception");
input.next();
} catch (NoSuchElementException e) {
System.out.println("No Such Element Exception");
input.next();
}
}
input.close();
return students;
}
我正在创建一个程序,该程序读取一个文本文件,其中列出了学生的名字、姓氏、ID、电子邮件、散列密码和最大学分。文本文件的每一行都有一整套由逗号分隔的每个元素。我希望程序读取文件,从每一行创建一个学生对象(我已经创建并测试了 Student 类,包括所有 getter 和 setter),并将学生对象排列在数组列表中。程序在 NoSuchElementException 处循环,并且只读取文本文件的第一行,而忽略接下来的 9 行。我不确定我的 try-catch 语句应该采用什么确切格式以确保它不会无限循环.
【问题讨论】:
-
看起来你正在处理一个csv文件,所以你应该使用一个csv阅读器库
标签: java while-loop try-catch