Explain Codes LogoExplain Codes Logo

How can I read input from the console using the Scanner class in Java?

java
scanner
input-validation
try-catch
Anton ShumikhinbyAnton Shumikhin·Sep 2, 2024
TLDR

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.

import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter text: "); String text = input.nextLine(); // input captured here System.out.println("Input was: " + text); // output here } }

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.

Scanner scan = new Scanner(System.in); // For a username, typically a String System.out.print("Enter your username: "); String username = scan.nextLine(); // Nice! Did you pick this username at random?😄 // For a single integer input System.out.print("Enter your age: "); int age = scan.nextInt(); scan.nextLine(); // Sneaky move: Clear that buffer

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:

try { // Scanner magic goes here } catch (Exception e) { System.out.println("Ouch! An error popped out: " + e.getMessage()); // Handle with grace! }

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:

System.out.print("Enter your email: "); String email = scan.next("\\S+@\\S+\\.\\S+"); // That's an email fit for a king!

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():

BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); int number = Integer.parseInt(reader.readLine()); // Because who needs strings when you have integers?

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.