I have a console application with a main method and some methods that I call from main. There, I want to ask the user for some input, for which I use the Scanner class.
Here's my problem:
I find there is no way to use Scanner when reading inputs from outside main without random exceptions or unexpected behaviour. I have tried two approaches:
- Having a
Scannerglobal variable in the class containingmain. Then I use this sameScannerin all functions in that same class. - In every function I need to ask for input, I declare a new
Scannervariable, use it, andcloseit before exiting the function.
1. makes Scanner try to read twice. I mean, I have a sc.readLine in a function and when I exit that function I have another sc.readLine in main. I input once and the two readLine lines get executed, the second one reading an empty String.
2. throws Exception (base class Exception) when I call any sc.readLine for a second time during the execution of the program.
I have also noticed that any other method other than readLine is going to read various items on the same line. For example, line "10 20 30 40" would execute 4 sc.nextInt calls.
TL;DR: how do you use Scanner in a console application?