0

I am getting this error when I try to run my program

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

I am trying to write an object to a txt file 'student.txt'. I have checked that the text file is in the correct folder, and that I have lines to be read. The program is supposed to read line by line and then create an object from those lines.

here is what the code looks like, any help would be greatly appreciated thanks.

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 Answers 2

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

You are doing hasNextLine() check only once. But you are reading 4 lines in.nextLine();.

2
  • so should i take out the (in.hasNextLine()) from the loop? I'm not exactly sure what you mean I can do, sorry! Jan 17, 2013 at 19:25
  • oh yeah, you mean to just take out the while loop! thanks it worked a charm :) Jan 17, 2013 at 19:30
0

The problem is your code assume that each student record consists of four lines, but you have less number of lines for a particular student. Consider a file that consist of following entries (left number is the line number):

  1. a1
  2. che
  3. b1
  4. 21
  5. a2
  6. che
  7. b2
  8. 22
  9. a3
  10. chem
  11. b3

running the following code will create a similar error you have faced as there are only three lines for the third (a3) student. Check your input files.

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.