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' に書き込もうとしています。テキスト ファイルが正しいフォルダーにあること、および読み取る行があることを確認しました。プログラムは、1 行ずつ読み取り、それらの行からオブジェクトを作成することになっています。

これがコードの外観です。どんな助けでも大歓迎です。

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

問題は、各学生レコードが 4 行で構成されていると想定しているコードですが、特定の学生の行数が少ないことです。次のエントリで構成されるファイルを考えてみましょう (左の数字は行番号です)。

  1. a1
  2. チェ
  3. b1
  4. 21
  5. a2
  6. チェ
  7. b2
  8. 22
  9. a3
  10. 化学薬品
  11. b3

次のコードを実行すると、3 番目 (a3) の生徒には 3 行しかないため、直面したのと同様のエラーが発生します。入力ファイルを確認してください。

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 に答える