Error building an Employee object from a .txt file Exception: java.util.NoSuchElementException: No line found

1

Good morning Community:

I have the sgt txt file.

With the following code I try to read the file and build as many Employee objects as lines have the mentioned file.

Main method:

The methods that do the whole operation:

The exception I get is the following:

I really do not know where to include the method hasNextLine () I thought that with the cycle for enough to do the route of the file.

Thank you very much for your time and help. DAVID.

    
asked by David Leandro Heinze Müller 22.10.2016 в 17:52
source

2 answers

1

You have 2 in.nextLine() and you only need 1. The problem is that you only have 3 employees and you do your loop 3 times starting at the second employee. So in the third round, you can not find any lines.

The first nextLine() is just before declaring the array or vector employees. When you do this, you position yourself in "Carl" for example. But, (already started your for) in your readEmployee method, you have another in.nextLine() that positions you in "Harry", that is, you jump to "Carl".

Your loop makes its first round with "Harry", it makes the second with "Tony", and when doing the 3rd round, it sends you the exception.

    
answered by 22.10.2016 / 18:03
source
1

Your problem is when you read the number of employees:

String[] size = in.nextLine().split(":"); //Saltas a la segunda línea
int n = Integer.parseInt(size[1]);
in.nextLine(); //Saltas a la tercera línea

Since if you look at your code in the first line you are already jumping to the second line with the nextLine method. In your third line of code (of which I copied above) you jump again to the third line so your code starts reading the employees from the third line and if you try to read your employees, the last employee (according to your code) will try to read it in the 5th line, which does not exist.

Using a nextLine method without saving the value, you should only use it when you use nextInt , nextDouble , etc ... that only read a value and leave the cursor on the same line but not when you read the line whole.

I have forgotten how you can solve your error although I think it is quite obvious. Remove your line in.nextLine(); , which jumps to your third line and your code will work without problems.

    
answered by 22.10.2016 в 18:07