private ArrayList<Student> students;
public void loadFromFile(String x){
try {
    FileReader reader = new FileReader(x);
    Scanner in = new Scanner(reader);
    int lineNumber = 1;
    while (in.hasNextLine())
      String name = in.nextLine();
      int score = in.nextInt();
      students.add (new Student(name, score));


Hey Guys i am getting unknown errors when trying to read students name and score from a file and store in an arraylist. Could I please get some information as to what these errors mean and ideas how to fix? Thanks in advance!

5 Years
Discussion Span
Last Post by jalpesh_007

What do you mean by unknown errors? Are you getting an exception, or is it giving you unexpected results? Give some more detail. Also, an example of your test input.


If you have an error message you should ALWAYS post the complete text of the message when asking for help. Th exact wording of the message tells us a lot, including the line number inthe program it refers to.
In the meantime, you haven't shown any code to initialise the students variable or create a new ArrayList for it to refer to.

Edited by JamesCherrill


OK, back from testing. My first instinct was correct...

The way you accept the input from file is causing the problem - nextLine() and then nextInt(). If the data in your file is formatted below, you would get InputMismatchException.

Student Name
Student Name

The reason is that after your nextLine() to obtain the first student name, the next token being read would be the beginning of the 2nd line. You then obtain the next value using nextInt() which would still be correct. However, the next token will be at the end of the 2nd line which has not passed the new line yet. When you read the second student name in, the name read in will be an empty string, and the next token to be read is at the beginning of the 3rd line which is the second student name. Then you attempt to use nextInt() to get the integer from the supposed to be string. That would cause the program to throw the exception.

Now, let say your data format is as follows:

Student Name

Student Name


This would give you the same error with a little bit different scenario. This time, the third line is an empty line, so nextInt() will get an empty line which cause the same error.

The only data format that would run on your current program is as follows:

Student Name
Score Student Name
Score ...

Why does this format work? Because the next token being read will not go to the next line until the nextLine() is read. However, I doubt that your program expects you to have this format in your data file.

Now, you need to clarify your data format and requirements of the program.

Edited by Taywin

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.