Welcome to the CSC Q&A, where you can get help (and share your knowledge) about computer science!

What purpose would there be for having multiple scanner objects in a single program?

+2 votes
Edited to fix some errors*

Is there a reason why you might use multiple instances of the scanner (e.g., console1, console2, etc.)?
asked Oct 10 in CSC 211 (F17) by Jacob Gholson (780 points)
edited Oct 10 by Jacob Gholson

2 Answers

+1 vote
Scanners can be used to read multiple things, such as user input, file data, or even just to parse through strings. A program might, for instance, ask the user for the name of a file using the first Scanner object, and then use a second Scanner object to read the data from that file.
answered Oct 10 by Vecna (3,748 points)
But why not just use the same one for everything?
When you initialize a scanner object, you tell it what it will read in, and you can't change that. So if you want to be able to read from more than one thing at the same time, you need multiple scanners.
Scanner is an object, you can assign it a pointer to a file or console input. You can change the pointer at any point to point it to a file instead. Usually you do need to parse through only one, maybe two things at any given time so most instances will only require 1 scanner. But assuming Scanners are unique and not a dynamic Object seems obstructive. Example, you have a Scanner read a file with some data in it. Instead of reading through the entire file you might just grab the first 100 lines and wait for the user to need more lines of the file. You will just leave the Scanner at that point and wait. There are ways around doing this such as assigning it to a variable, but TL;DR a Scanner is an object, you can work around having multiple scanners, but to think of it as a privilaged object is just not the case.
+1 vote
And for your information, scanner is very computational expensive so you want to close a scanner after you are done or reassign it to a new Scanner so that the garbage collector can collect it for you.
answered Oct 11 by Dat Tran (2,584 points)
How comutational expensive is it? Isn't it just an iterator going through a data file? It can be assumed there is more information even after you are done with it which will cause it to be left untouched by the garbage collector, but this is true for most objects, you should really set it to null or remove it's references another way.
Lol, very dedicated. It is because scanner does a lot of redundant parsing usually with char. Therefore, on pc it is not that bad but when you start using it on Android then it is very slow. It is true that you can have multiple scanners, so I need to adjust that but rule of thumb is often iterate through something and save it somewhere and 1 scanner for 1 object.
I totally agree you should reduce scanner use if possible. And when done cleanup. Thanks, that was informative. Have an upvote!
...