bugl
bugl
HomeLearnPatternsPathsSearch
HomeLearnPatternsPathsSearch

Loading lesson path

Learn/Java/Java Classes
Java•Java Classes

Java User Input (Scanner)

Flash cards

Review the key moves

1/4
Core idea

What is the main idea behind Java User Input (Scanner)?

Lesson checks

Practice each idea before moving on

Short Mimo-style checks built from this lesson's code, terms, and sequence.

1Quick choice

Which statement best captures the main point of this lesson?

2Fill blank

Complete the missing token from the example code.

import java.util.Scanner; // Import the Scanner ___
3Order

Put the learning moves in the order that makes the concept easiest to apply.

If you don't know what a package is, read our Java Packages Tutorial .
To use the Scanner class, create an object of the class and use any of the available methods found in the Scanner class documentation.
The Scanner class is used to get user input, and it is found in the java.

Java User Input

The Scanner class is used to get user input, and it is found in the java.util package.

To use the Scanner class, create an object of the class and use any of the available methods found in the Scanner class documentation. In our example, we will use the nextLine() method, which is used to read Strings:

Example

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
 }
}

If you don't know what a package is, read our Java Packages Tutorial .

Input Types

In the example above, we used the nextLine() method, which is used to read Strings. To read other types, look at the table below:

MethodDescription

In the example below, we use different methods to read data of various types:

Example

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 input int age = myObj.nextInt(); double salary = myObj.nextDouble();
 // Output input by user System.out.println("Name: " + name); System.out.println("Age: " + age); System.out.println("Salary: " + salary);
 }
}

Note

If you enter wrong input (e.g. text in a numerical input), you will get an exception/error message (like "InputMismatchException").

You can read more about exceptions and how to handle errors in the Exceptions chapter .

Previous

Java Enum Constructor

Next

Java Date and Time