How to get the user input in Java?
Here's a simple way to get text input using Java's Scanner
:
Deep diving into user inputs
Eating up different types of inputs
The Scanner class is like a chameleon, it can morph according to the input type. It has nextInt()
for integer, nextDouble()
for double, and so on:
Don't forget to prompt the user before getting each input, manners matter even in code!
Don't leave your scanner open
Alas the busy Scanner, if forgotten to be closed, can cause resource leaks:
Rolling with the unexpected
The seas of user inputs can be treacherous. Handle exceptions well when user sends something unexpected:
Exploring the alternate realities
Not a fan of Scanner
or want more spice? Use Console
for interactive prompts and password inputs, or choose BufferedReader
for large inputs:
Beware, shh, hear it from the wise, Console
might not work in some IDEs.
Gift wrapping whole user interaction
Dealing with past - Deprecated methods
Beware of the past! Deprecated methods like readLine
from DataInputStream
might look tempting but can bite. Remember - age sometimes comes without wisdom.
Building your own Jarvis
Why not use this newfound knowledge to do something cool - like a simple console calculator!
Select the right tool (method), for the right job (expected input type):
Advanced etiquettes - Inline prompts
"Can you put the prompt right next to my input?" - Sure, here it is!
The cultural nuances
Different locales have different ways of reading numbers. Ensure consistency by setting your scanner's locale:
Was this article helpful?