Scanner Class

Naveen AnamaneniUpdated · 6 min read

A billing counter program isn't much use if every price is fixed in the code. Real programs ask: what's your name, how many tickets, which date. The most common way for a beginner Java program to read what the user types is the Scanner class. It reads from the keyboard and turns the text into the types you need: int, double, String.

Your First Scanner

Greeting.java▶ Try it
import java.util.Scanner;
 
public class Greeting {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Your name: ");
        String name = sc.next();
        System.out.print("Tickets: ");
        int tickets = sc.nextInt();
        int fare = tickets * 120;
        System.out.printf("%s booked %d tickets, Rs. %d%n",
                name, tickets, fare);
    }
}
Output
Your name: Tickets: Srihitha booked 3 tickets, Rs. 360

When you run it yourself and type Srihitha and 3, the screen looks like this:

Terminal
Your name: Srihitha
Tickets: 3
Srihitha booked 3 tickets, Rs. 360

How it works

  1. Line 1 imports Scanner from the java.util package. Without it, the compiler can't find the class.
  2. Line 5 creates a Scanner that reads from System.in, the keyboard.
  3. Line 7: next() reads one word. Line 9: nextInt() reads one whole number.
  4. print (not println) keeps the cursor next to each prompt, so the user types on the same line.

The output block above shows the prompts and the result on one line because what you type isn't part of the program's output.

Try it yourself: type Srihitha Anamaneni as the name. Why does the program crash or behave strangely?

The Reading Methods

MethodReadsReturns
next()One word (up to a space or new line)String
nextLine()The rest of the current line, spaces includedString
nextInt()One whole numberint
nextLong()One whole numberlong
nextDouble()One decimal numberdouble
nextBoolean()true or falseboolean
hasNextInt()Checks whether the next word is a whole number, without reading itboolean

How Scanner Sees Your Input

Scanner treats input as a stream of characters and splits it into tokens: pieces separated by spaces or new lines. The next...() methods take one token each. nextLine() is different: it takes everything up to the end of the current line.

Why nextLine after nextInt returns an empty string

The nextInt-Then-nextLine Trap

This is the most common Scanner bug. Read a number, then a full line:

Trap.java▶ Try it
import java.util.Scanner;
 
public class Trap {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int age = sc.nextInt();
        String name = sc.nextLine();
        System.out.println("[" + name + "] is " + age);
    }
}
Output
[] is 25

nextInt() reads 25 but leaves the Enter you pressed after it waiting in the input. Line 7's nextLine() reads up to that new line, finds nothing before it, and returns an empty string. The name you typed is never read.

The fix: after nextInt() (or nextDouble(), next()), call sc.nextLine(); once to throw away the rest of that line, then read the real line:

Fixed.java▶ Try it
import java.util.Scanner;
 
public class Fixed {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int age = sc.nextInt();
        sc.nextLine();
        String name = sc.nextLine();
        System.out.println("[" + name + "] is " + age);
    }
}
Output
[Srihitha Anamaneni] is 25

When the User Types Something Wrong

If nextInt() finds abc instead of a number, it throws an InputMismatchException and the program stops. Check first with hasNextInt():

SafeAge.java▶ Try it
import java.util.Scanner;
 
public class SafeAge {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        if (sc.hasNextInt()) {
            System.out.println("Age: " + sc.nextInt());
        } else {
            System.out.println("Please type a whole number");
        }
    }
}
Output
Please type a whole number

Common Mistakes

Forgetting the import. Without import java.util.Scanner; you get cannot find symbol: class Scanner.

Using next() for names with spaces. next() stops at the first space. Use nextLine() for full names and addresses.

Reading a line right after a number. Add the extra nextLine(), as shown above.

Interview Corner

Why does nextLine() return an empty string after nextInt()?

nextInt() reads only the digits and leaves the new-line character from the Enter key in the input. The following nextLine() reads up to that new line and returns the empty text before it. Call nextLine() once to discard it, or read every line with nextLine() and convert with Integer.parseInt.

What is the difference between next() and nextLine()?

next() returns the next token, stopping at a space or new line. nextLine() returns everything up to the end of the current line, including spaces, and moves past the new line.

Practice

  1. Easy: Ask for two whole numbers and print their sum and their product.
  2. Harder: Ask for a passenger's age (a number) and then their full name (with spaces). Print Srihitha Anamaneni, 25. Make sure the name isn't empty.

Quick check: Scanner

4 questions
1Which package must you import to use Scanner?
2The user types Srihitha Anamaneni. What does next() return?
3Why can nextLine() return "" right after nextInt()?
4The user types abc and the program calls nextInt(). What happens?

Key Takeaways

Was this tutorial helpful?

Lesson 49 of 482