Reputation: 67
What is the advantage or use of using multiple scanner objects in a program?
Scanner sc = new Scanner(System.in);
as opposed to something like
Scanner sc1 = new Scanner(System.in);
Scanner sc2 = new Scanner(System.in);
in the same program.
Upvotes: 3
Views: 77
Reputation: 285405
I can see no advantage to the second bit of code:
Scanner sc1 = new Scanner(System.in);
Scanner sc2 = new Scanner(System.in);
and in fact there is some risk, risk if you close one Scanner (and thus the System.in
) before the other Scanner is done using it.
Instead, I can definitely see using more than one Scanner at times, but only one primary Scanner linking to System.in
. Other Scanners can parse a line obtained. For example, use the main Scanner to get each line of text, and then use a second Scanner that has been fed the individual lines to parse the information held in the lines.
e.g.,
Scanner sc = new Scanner(System.in);
while (sc.hasNextLine()) {
String line = sc.nextLine();
Scanner lineScanner = new Scanner(line);
//.... parse line...
lineScanner.close();
}
sc.close();
Upvotes: 9