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

A simple example to illustrate how java.util.Scanner works would be reading a single integer from System.in. It’s really quite simple. Scanner sc = new Scanner(System.in); int i = sc.nextInt(); To retrieve a username I would probably use sc.nextLine(). System.out.println(“Enter your username: “); Scanner scanner = new Scanner(System.in); String username = scanner.nextLine(); System.out.println(“Your username is ” … Read more

How to handle infinite loop caused by invalid input (InputMismatchException) using Scanner

As per the javadoc for Scanner: When a scanner throws an InputMismatchException, the scanner will not pass the token that caused the exception, so that it may be retrieved or skipped via some other method. That means that if the next token is not an int, it throws the InputMismatchException, but the token stays there. … Read more

What’s the difference between next() and nextLine() methods from Scanner class?

I always prefer to read input using nextLine() and then parse the string. Using next() will only return what comes before the delimiter (defaults to whitespace). nextLine() automatically moves the scanner down after returning the current line. A useful tool for parsing data from nextLine() would be str.split(“\\s+”). String data = scanner.nextLine(); String[] pieces = … Read more

Scanner is skipping nextLine() after using next() or nextFoo()?

That’s because the Scanner.nextInt method does not read the newline character in your input created by hitting “Enter,” and so the call to Scanner.nextLine returns after reading that newline. You will encounter the similar behaviour when you use Scanner.nextLine after Scanner.next() or any Scanner.nextFoo method (except nextLine itself). Workaround: Either put a Scanner.nextLine call after … Read more

How to use java.util.Scanner to correctly read user input from System.in and act on it?

Idiomatic Example: The following is how to properly use the java.util.Scanner class to interactively read user input from System.in correctly( sometimes referred to as stdin, especially in C, C++ and other languages as well as in Unix and Linux). It idiomatically demonstrates the most common things that are requested to be done. package com.stackoverflow.scanner; import … Read more

Scanner is skipping nextLine() after using next() or nextFoo()?

That’s because the Scanner.nextInt method does not read the newline character in your input created by hitting “Enter,” and so the call to Scanner.nextLine returns after reading that newline. You will encounter the similar behaviour when you use Scanner.nextLine after Scanner.next() or any Scanner.nextFoo method (except nextLine itself). Workaround: Either put a Scanner.nextLine call after … Read more