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

Hock3yPlayer picture Hock3yPlayer · Aug 8, 2012 · Viewed 1.6M times · Source

How could I read input from the console using the Scanner class? Something like this:

System.out.println("Enter your username: ");
Scanner = input(); // Or something like this, I don't know the code

Basically, all I want is have the scanner read an input for the username, and assign the input to a String variable.

Answer

Rune Vikestad picture Rune Vikestad · Aug 8, 2012

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 " + username);

You could also use next(String pattern) if you want more control over the input, or just validate the username variable.

You'll find more information on their implementation in the API Documentation for java.util.Scanner