Ask coding questions

← Back to all posts
Scanner not closing/resetting
steehs1532 (2)

Hi, I need to be able to scan a file multiple times depending on user input and when I close my scanner and make a new one it doesn't seem to be opening up a new file.

Error Example:
What would you like to monitor? Please type 'animal', 'habitat', or 'exit'.
Details on lions
Details on tigers
Details on bears
Details on giraffes
Please type animal from the list above (ie. lion)
Animal - lion
Name: Leo
Age: 5
*Health concerns: Cut on left front paw
Feeding schedule: Twice daily
What would you like to monitor? Please type 'animal', 'habitat', or 'exit'.
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(
at Main.main(
exit status 1

Answered by vedprad1 (727) [earned 5 cycles]
View Answer
vedprad1 (727)

The reason why this is not working is because once you close a Scanner, you cannot open it again with the same Stream. However, with sufficient knowledge of ArrayLists, I fixed the problem. The final code is here:

What I did:

Line 4: import ArrayList

Line 8: make an ArrayList

Line 30: add a new Stream to the ArrayList

Line 31: make a new Scanner from the new Stream

That's all you have to do. EVery time the while loop runs, it makes a new Stream for the Scanner to operate on. I did not do it yet for the habitat file, so that is up to you. Just copy my code into your file, and it will work.

If this answers your question, please check the check mark on the left of this message. Thanks and Good Luck!

vedprad1 (727)

I might be able to help you on this. However, the url you have posted is the final product, not the actual code. Is this your code: ? If it is, I will check it and see if I can find a mistake.

steehs1532 (2)

@vedprad1 Yes, sorry that is the code