Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the advantage of using multiple scanners?

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.

like image 833
Alex Lay-Calvert Avatar asked Dec 17 '25 20:12

Alex Lay-Calvert


1 Answers

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();
like image 177
Hovercraft Full Of Eels Avatar answered Dec 20 '25 11:12

Hovercraft Full Of Eels



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!