How can I read input from the console using the Scanner class in Java?
Harness the Scanner
class to read console data with new Scanner(System.in)
. Invoke scanner.nextLine()
for capturing full lines or scanner.nextInt()
for integers.
Execute it, input text, hit Enter, and look at the returned results.
Scanner mastery: Beyond basics
Dealing with diverse input types
Capture different data types like strings or integers using specific Scanner
methods.
Always remember to clear the buffer after numeric inputs with scan.nextLine()
. It's like cleaning up after a meal to avoid leftover skipped inputs.
Error-proofing with try-catch
Envelop the Scanner in a try-catch block to tackle InputMismatchException and NoSuchElementException:
Tidy up after usage
Close the Scanner with scan.close()
after using—like thanking the chef after a delicious meal. This frees up system resources, preventing unwanted memory leaks. A finally block or try-with-resources can auto-close the Scanner.
Level up: RegEx, synchronization, and customized delimiters
Input validation with RegEx
Validate inputs against specific patterns using next(String pattern)
. For instance, to capture a valid email, do this:
Sync & control with BufferedReader
BufferedReader
adds synchronized and more controlled line-by-line reading. Plus, you can straighforwardly transform strings to integers with Integer.parseInt()
:
Customize delimiters and thread safety
useDelimiter()
is your magic tool to set a custom delimiter for parsing tokens in structured inputs like CSV files.
In multi-threaded environments, make your Scanner
thread-safe with external synchronization.
Was this article helpful?