How do I get simple keyboard input (an integer) from the user in the console in Java? I accomplished this using the java.io.*
stuff, but it says it is deprecated.
How should I do it now?
How do I get simple keyboard input (an integer) from the user in the console in Java? I accomplished this using the java.io.*
stuff, but it says it is deprecated.
How should I do it now?
You can use Scanner class like this:
You can use Scanner class
Import first :
Then you use like this.
Side note : If you are using
nextInt()
withnextLine()
you probably could have some trouble causenextInt()
does not read the last newline character of input and sonextLine()
then is not gonna to be executed with desired behaviour. Read more in how to solve it in this previous question Skipping nextLine using nextInt.You can also make it with BufferedReader if you want to validate user input, like this:
Because Scanner class won't allow you to do it, or not that easy...
And to validate you use "try-catch" calls.
Let me know if you have any questions. Fairly self-explanatory. I commented the code so you can read it. :)
You can use Scanner to get the next line and do whatever you need to do with the line entered. You can also use JOptionPane to popup a dialog asking for inputs.
Scanner example:
JOptionPane example:
You will need these imports:
A complete Java class of the above
If you have Java 6 (You should have, btw) or higher, then simply do this :
Please remember to do :
Thats it!