';java.util.NoSuchElementException:未找到任何行';使用scanner类

';java.util.NoSuchElementException:未找到任何行';使用scanner类,java,exception,java.util.scanner,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.

当我试图运行我的程序时,我遇到了这个错误

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));
    }
}
公共类StudentDAO实现DAO{
ArrayList studentList=新建ArrayList();
字符串outputFileName=“student.txt”;
File outputFile=新文件(outputFileName);
扫描仪输入;
public StudentDAO()引发异常{
试一试{
in=新扫描仪(新BufferedReader(新文件读取器(outputFile));
}捕获(FileNotFoundException ex){
抛出新的异常(例如getMessage());
}
}
@凌驾
公开作废{
while(在.hasNextLine()中){
String studentName=in.nextLine();
String studentClass=in.nextLine();
字符串teacher=in.nextLine();
String studentAge=in.nextLine();
int studentagent=Integer.parseInt(studentAge);
添加(新学生)(学生姓名、学生班级、教师、,
学生精神);
}
}

你正在做的是<代码> HasNeXRealTo()/Cug >只检查一次。但是你正在读4行<代码> in .NestLoin();./P>> P>问题是你的代码假设每个学生记录由四行组成,但是你对于一个特定的学生的行数要少。考虑一个由下列条目组成的文件(左数是行号):

  • a1
  • b1
  • 二十一,
  • a2
  • b2
  • 二十二
  • a3
  • 化学
  • 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());
     }
    

    那么我应该从循环中取出(in.hasNextLine())吗?我不太确定你的意思是我能做什么,对不起!哦,是的,你的意思是只取出while循环!谢谢,它很有效:)
    while(in.hasNextLine()){
       System.out.println(" "+in.nextLine());
       System.out.println(" "+in.nextLine());
       System.out.println(" "+in.nextLine());
       System.out.println(" "+in.nextLine());
     }