Skip to content
Fix Code Error

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

March 13, 2021 by Code Error
Posted By: Anonymous

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.

Solution

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

Answered By: Anonymous

Related Articles

  • How can I resolve Web Component Testing error?
  • Scanner is skipping nextLine() after using next() or…
  • Examples of GoF Design Patterns in Java's core libraries
  • JUNIT @ParameterizedTest , Parameter resolution Exception
  • Using scanner.nextLine()
  • There's an InputMismatchException, how do i fix it?
  • Problem while using user insert for getter
  • Why is scanner reading no input and exiting function?
  • How can I update specific parts of a text file in java?
  • How to read strings from a Scanner in a Java console…

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

How do I limit the number of rows returned by an Oracle query after ordering?

Next Post:

Encode URL in JavaScript?

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

  • Get code errors & solutions at akashmittal.com
© 2022 Fix Code Error