RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Jun 24, 2021

How to Accept User Input in Java

To accept user input from someone using your software, Java provides the Scanner class, which is part of the java.util package. We will look at how to use the java.util package, the Scanner class, and the nextLine() method in this Java programming tutorial for developers.

Below is an example program showing how to use the nextLine() method in Java to accept user input:

// How to import the Scanner class
import java.util.Scanner; 
class Main {
  public static void main(String[] args) {
// Create the Scanner
	Scanner superName = new Scanner(System.in); 
    System.out.println("Enter a Super Hero Name:");
// Read User Input and store in a String
	String heroName = superName.nextLine();
// Print heroName
    System.out.println("Your Super Hero Name is: " + heroName);

The output from running this program would be:

Enter a Super Hero Name:

Your Super Hero Name Is: 

The exact output will be slightly different depending upon which name the user input at the prompt.

Accepting Other User Input Types in Java

While the nextLine() method is used to accept user input in the form of String data types, Java also provides a way to accept the following data types, including the following methods:

nextBoolean(): This method is used to read boolean values from a user. nextByte(): This method is used to read a byte value from a user. nextDouble(): This method is used to read double values from a user. nextFloat(): This method is used to read floating point numbers or float values from a user. nextInt(): This method is used to read integer or int values from a user. nextLine(): As discussed earlier in this article, this method is used to read String values from a user. nextLong(): This method is used to read long values from a user. nextShort(): This method is used to read short values from a user.

James Payne
Close Icon
Thanks for your registration, follow us on our social networks to keep up-to-date