'java.util.NoSuchElementException:找不到行'使用scanner类

时间:2013-01-17 18:29:49

标签: java exception java.util.scanner

我在尝试运行程序时收到此错误

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));
    }
}

2 个答案:

答案 0 :(得分:2)

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

您正在进行hasNextLine()次检查。但是你正在读4行in.nextLine();

答案 1 :(得分:0)

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

  1. A1
  2. B1
  3. 21
  4. A2
  5. B2
  6. 22
  7. A3
  8. 化学
  9. B3
  10. 运行以下代码会产生类似的错误,因为第三个(a3)学生只有三行。检查输入文件。

    while(in.hasNextLine()){
       System.out.println(" "+in.nextLine());
       System.out.println(" "+in.nextLine());
       System.out.println(" "+in.nextLine());
       System.out.println(" "+in.nextLine());
     }