Java Input with Scanner

What Is Scanner?

In Java, Scanner is a class used to read user input from the keyboard.

To use it, you must import java.util.Scanner and create a Scanner object.

Loading...
Output:

Importing Scanner

Scanner is part of the java.util package, so it must be imported before the class.

Loading...
Output:

Creating a Scanner Object

Use new Scanner(System.in) to read input typed by the user.

  • Scanner is the class name
  • input is the variable name
  • System.in means keyboard input
Loading...
Output:

Reading Strings

Use nextLine() to read a full line of text and next() to read only one word.

Loading...
Output:

Reading Numbers

Scanner has different methods for different data types.

  • nextInt() – reads an integer
  • nextDouble() – reads a decimal number
  • nextBoolean() – reads true or false
  • nextLine() – reads a full line of text
Loading...
Output:

The nextLine() Problem

After using nextInt(), nextDouble(), or next(), the leftover newline can cause nextLine() to be skipped.

Fix it by adding an extra nextLine() before reading the full line.

Loading...
Output:

Using Input in Calculations

Input values can be stored in variables and used in calculations.

Loading...
Output:

Input Validation Basics

Use methods like hasNextInt() or hasNextDouble() to check input before reading it.

Loading...
Output:

Practice Question

Create a program that asks the user for their name, age, and favorite programming language. Then print a sentence using all three values.

Example Output:
Enter your name:
Alice
Enter your age:
20
Enter your favorite programming language:
Java
Alice is 20 years old and likes Java.
Loading...
Output:

Hint: If you use nextInt() before nextLine(), remember to clear the leftover newline.

Need Help?

Ask the AI if you need help understanding or want to dive deeper in any topic