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

21st May 2020, 6:20 AM
Zach Janzen
5 odpowiedzi
+ 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();
21st May 2020, 6:34 AM
ChaoticDawg
ChaoticDawg - avatar
+ 1
Thanks. I’m really new to Java so this helps me quite a bit.
21st May 2020, 6:44 AM
Zach Janzen
+ 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
21st May 2020, 6:50 AM
ChaoticDawg
ChaoticDawg - avatar
+ 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.
21st May 2020, 6:56 AM
ChaoticDawg
ChaoticDawg - avatar
+ 1
thank you
21st May 2020, 7:00 AM
Zach Janzen