[英]java.util.NoSuchElementException: No line found - Scanner/PriintWriter Issues
[英]'java.util.NoSuchElementException: No line found' using scanner class
嘗試運行程序時出現此錯誤
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));
}
}
while (in.hasNextLine()) {
String studentName = in.nextLine();
String studentClass = in.nextLine();
String teacher = in.nextLine();
String studentAge = in.nextLine();
}
您正在執行hasNextLine()
檢查一次。 但是您正在in.nextLine();
中讀取4行in.nextLine();
。
問題是您的代碼假定每個學生記錄由四行組成,但是對於特定學生而言,行數較少。 考慮一個由以下條目組成的文件(左邊的數字是行號):
運行以下代碼將產生您遇到的類似錯誤,因為第三位(a3)學生只有三行。 檢查您的輸入文件。
while(in.hasNextLine()){
System.out.println(" "+in.nextLine());
System.out.println(" "+in.nextLine());
System.out.println(" "+in.nextLine());
System.out.println(" "+in.nextLine());
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.