0

当我尝试运行我的程序时出现此错误

Exception in thread "main" java.util.NoSuchElementException: No line found
    at java.util.Scanner.nextLine(Scanner.java:1516)
    at studenttextwrite.StudentDAO.open(StudentDAO.java:37)
    at studenttextwrite.StudentTextWrite.main(StudentTextWrite.java:33)
Java Result: 1

我正在尝试将对象写入 txt 文件“student.txt”。我检查了文本文件是否在正确的文件夹中,并且我有要读取的行。该程序应该逐行读取,然后从这些行创建一个对象。

这是代码的样子,任何帮助将不胜感激,谢谢。

public class StudentDAO implements DAO {

ArrayList<Student> studentList = new ArrayList();
String outputFileName = "student.txt";
File outputFile = new File(outputFileName);
Scanner in;

public StudentDAO() throws DAOException {
    try {
        in = new Scanner(new BufferedReader(new FileReader(outputFile)));
    } catch (FileNotFoundException ex) {
        throw new DAOException(ex.getMessage());
    }
}

@Override
public void open() {
    while (in.hasNextLine()) {
        String studentName = in.nextLine();
        String studentClass = in.nextLine();
        String teacher = in.nextLine();
        String studentAge = in.nextLine();
        int studentAgeInt = Integer.parseInt(studentAge);
        studentList.add(new Student(studentName, studentClass, teacher,
                studentAgeInt));
    }
}
4

2 回答 2

2
while (in.hasNextLine()) {
        String studentName = in.nextLine();
        String studentClass = in.nextLine();
        String teacher = in.nextLine();
        String studentAge = in.nextLine();
}

hasNextLine()只做一次检查。但是您正在阅读 4 行in.nextLine();

于 2013-01-17T18:31:18.560 回答
0

问题是您的代码假设每个学生记录由四行组成,但您对特定学生的行数较少。考虑一个包含以下条目的文件(左边的数字是行号):

  1. a1
  2. b1
  3. 21
  4. a2
  5. b2
  6. 22
  7. a3
  8. 化学
  9. b3

运行以下代码将产生您遇到的类似错误,因为第三个 (a3) 学生只有三行。检查您的输入文件。

while(in.hasNextLine()){
   System.out.println(" "+in.nextLine());
   System.out.println(" "+in.nextLine());
   System.out.println(" "+in.nextLine());
   System.out.println(" "+in.nextLine());
 }
于 2013-01-17T19:25:28.840 回答