0
Java
So Iāve posted 2 other questions similar to this but I donāt think I quite worded them properly. Basically, I would like to know how I can add more than one scanner to my java code. I think thatās the right way to word what Iām trying to ask
5 Answers
+ 1
You should only use 1 scanner for a given input stream within a given scope or you will most likely have problems. Instead of using multiple scanners use the same scanner and utilize the different methods of the scanner class to get the input of different types from the stream. Keep in mind that the methods that only consume up to the 1st whitespace or type, such as next(), nextInt(), nextDouble(), etc, will leave the remaining newline character '\n' in the stream and will be consumed by the next method call that will accept it. So, if planning on using a method such as nextLine() after the use of a call to nextInt(), etc, with that scanner an additional call to nextLine() to consume the newline character will be needed.
....
Int i = scanner.nextInt();
scanner.nextLine(); // just consume '\n' don't save
String str = scanner.nextLine();
+ 1
Thanks. Iām really new to Java so this helps me quite a bit.
+ 1
Here's an example. Just uncomment the code to see it breaks when you try to run it.
https://code.sololearn.com/cfPZRhgN9vjK/?ref=app
+ 1
Actually, I'm going to take 1 thing back and change my answer a bit. It doesn't really matter so much if they are in the same scope or not, but rather that if they are both using the same stream and both are still a current instance at the same time. So, one of them needs to be destroyed, prior to the other attempting to utilize the same stream. Otherwise, they will conflict with each other.
+ 1
thank you