Java User Input with Scanner - Capture Console Input Easily

Discover how to use Java's Scanner class to read user input directly from the console. This versatile tool in the java.util package allows for simple and efficient user input handling, whether you’re capturing strings, integers, or other data types. Learn through examples and enhance your Java applications with interactive user inputs.



Java User Input (Scanner)

The Scanner class in Java is used to get user input from the console, and it is part of the java.util package.

Example of Using Scanner

To use the Scanner class, create an object of the class and use its methods to read user input. In the example below, we use the nextLine() method to read a String:

Syntax

import java.util.Scanner;  // Import the Scanner class

class Main {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in);  // Create a Scanner object
System.out.println("Enter username");

String userName = myObj.nextLine();  // Read user input
System.out.println("Username is: " + userName);  // Output user input
}
}
Output

Enter username
John
Username is: John

Input Types

The Scanner class provides various methods to read different types of input:

Method Description
nextBoolean() Reads a boolean value from the user
nextByte() Reads a byte value from the user
nextDouble() Reads a double value from the user
nextFloat() Reads a float value from the user
nextInt() Reads an int value from the user
nextLine() Reads a String value from the user
nextLong() Reads a long value from the user
nextShort() Reads a short value from the user

Example: Reading Different Types of Input

In this example, we read different types of input (String, int, and double) using various Scanner methods:

Syntax

import java.util.Scanner;

class Main {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in);

System.out.println("Enter name, age and salary:");

// String input
String name = myObj.nextLine();

// Numerical inputs
int age = myObj.nextInt();
double salary = myObj.nextDouble();

// Output user input
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Salary: " + salary);
}
}
Output

Enter name, age and salary:
John
25
2500.50
Name: John
Age: 25
Salary: 2500.5

Note: If the input format does not match the expected type, Java throws an exception (e.g., InputMismatchException).

For more information on handling exceptions, refer to the Exceptions chapter.