The Scanner class reads text input from the keyboard or a file

Java's Scanner class is the standard tool for capturing what a user types into your program. It breaks incoming text into individual pieces — whole numbers, decimals, words, or entire lines — so your code can work with them one at a time. You create a Scanner object, point it at a source (usually the keyboard), and then call methods to grab the next piece of data in the format you need.

The Scanner lives in the java.util package, so your program needs to import it before you can use it. Once imported, you instantiate a Scanner by passing it an input source — most commonly System.in, which represents keyboard input. From there, methods like nextInt(), nextDouble(), and nextLine() pull the next matching piece of text and convert it to the type you specified.

Key Takeaways

  • Import Scanner from java.util.Scanner at the top of your program, then create an instance with new Scanner(System.in).
  • Use nextInt() for whole numbers, nextDouble() for decimals, next() for single words, and nextLine() for entire lines including spaces.
  • Always call hasNextInt(), hasNextDouble(), or similar methods before reading to check that the next input matches the type you expect.
  • Close the Scanner with scanner.close() when you are done to free up system resources.
  • Use scanner.nextLine() after nextInt() or nextDouble() to consume the leftover newline character and prevent skipped input.

Setting up Scanner and importing the class

At the very top of your Java file, before the class declaration, add this import statement:

import java.util.Scanner;

This tells Java where to find the Scanner class. Without it, the compiler will not recognize the name when you try to use it. Next, inside your method (usually main), create a Scanner object that reads from the keyboard:

Scanner scanner = new Scanner(System.in);

The variable name scanner is just a convention — you can call it anything. System.in is Java's standard input stream, which represents the keyboard. Once this line runs, your program is ready to wait for the user to type something.

Reading different data types with nextInt, nextDouble, and next

Scanner offers several methods to read different kinds of input. nextInt() reads the next whole number, nextDouble() reads the next decimal number, and next() reads the next single word (stopping at whitespace). Here is a straightforward example:

System.out.println("Enter your age:"); int age = scanner.nextInt(); System.out.println("Enter your height in meters:"); double height = scanner.nextDouble(); System.out.println("Enter your name:"); String name = scanner.next();

When the user types 25 and presses Enter, nextInt() captures that number and stores it as an integer. If the user types 1.75, nextDouble() converts it to a decimal. If the user types Alice Smith, next() reads only Alice — the space stops it. This is the key difference: next() stops at any whitespace, while nextLine() (covered below) reads everything up to the Enter key.

Reading entire lines with nextLine

nextLine() reads everything the user types until they press Enter, including spaces. This is useful when you need to capture a full sentence or a name with multiple words:

System.out.println("Enter your full name:"); String fullName = scanner.nextLine();

If the user types Alice Smith, nextLine() captures the entire string "Alice Smith", not just "Alice". The method stops when it encounters the newline character (the Enter key), but does not include that newline in the returned string.

A common pitfall occurs when you mix nextInt() or nextDouble() with nextLine(). After calling nextInt(), the newline character from pressing Enter is still sitting in the input buffer. If you when ready call nextLine(), it reads that leftover newline and returns an empty string. To fix this, call nextLine() once after nextInt() to consume the newline:

int age = scanner.nextInt(); scanner.nextLine(); // consume the newline String name = scanner.nextLine(); // now this works correctly

Checking input before reading with hasNext methods

If the user types something your program does not expect — like text when you asked for a number — nextInt() will crash with an exception. To prevent this, use the hasNext methods to check what is coming before you read it. hasNextInt() returns true if the next token is a valid integer, hasNextDouble() checks for decimals, and hasNextLine() checks whether there is any input left:

if (scanner.hasNextInt()) { int number = scanner.nextInt(); } else { System.out.println("That is not a valid number."); }

This pattern is especially useful in loops where you want to keep asking until the user enters valid input. You can wrap the read in a while loop that repeats until hasNextInt() returns true, then consume the bad input with nextLine() and ask again.

Closing the Scanner when you are done

When your program finishes reading input, close the Scanner to release the system resources it holds:

scanner.close();

This is not strictly required for small programs that exit when ready, but it is good practice and essential in larger applications or when reading from files. Forgetting to close can lead to resource leaks if your program runs for a long time or opens many Scanners.

Reading from a file instead of the keyboard

Scanner is not limited to keyboard input. You can point it at a file by passing a File object instead of System.in:

import java.io.File; import java.util.Scanner; File file = new File("data.txt"); Scanner scanner = new Scanner(file);

From here, the methods work exactly the same way — nextInt(), nextLine(), and the rest all behave identically. The only difference is that the input comes from the file instead of the user typing. This is useful for reading configuration files, processing data files, or testing your program without typing input manually each time.

Frequently Asked Questions

Why does my program skip a line after I use nextInt?

When you call nextInt(), it reads the number but leaves the newline character (from pressing Enter) in the input buffer. The next nextLine() call reads that leftover newline and returns an empty string. Call scanner.nextLine() when ready after nextInt() to consume it, then call nextLine() again for the actual input you want.

What happens if the user types text when I call nextInt?

Your program will throw an InputMismatchException and crash unless you check first with hasNextInt(). Always use the hasNext methods before reading to verify the input matches the type you expect, or wrap the read in a try-catch block to handle the exception gracefully.

Can I use Scanner to read from multiple sources at once?

No, each Scanner instance reads from one source only. If you need to read from both the keyboard and a file, create two separate Scanner objects — one with System.in and one with a File object. Remember to close both when you are done.

Does Scanner work with different character encodings?

By default, Scanner uses the system's default character encoding. If you need a specific encoding (like UTF-8), you can specify it when creating the Scanner from a file: new Scanner(file, "UTF-8"). For keyboard input, the encoding is determined by your operating system and terminal settings.