Skip to content

Scanner

This content is for Java. Switch to the latest version for up-to-date documentation.

The Scanner class in Java is used to get user input from various sources including the console (keyboard), files, and strings.

To use the Scanner class, you first need to import it:

import java.util.Scanner;

Then create a Scanner object:

// Create a Scanner object for console input
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = scanner.nextLine(); // Reads a line of text
System.out.print("Enter your age: ");
int age = scanner.nextInt(); // Reads an integer
System.out.print("Enter your height in meters: ");
double height = scanner.nextDouble(); // Reads a double
System.out.print("Enter a word: ");
String word = scanner.next(); // Reads until whitespace
MethodDescription
nextLine()Reads a line of text (until newline)
next()Reads the next token (word)
nextInt()Reads the next token as an int
nextDouble()Reads the next token as a double
nextBoolean()Reads the next token as a boolean
hasNext()Returns true if more tokens exist
hasNextLine()Returns true if more lines exist

When you use nextInt() or other non-line methods followed by nextLine(), you may encounter issues because nextInt() doesn’t consume the newline character:

// Issue example
int number = scanner.nextInt(); // User enters "42" and presses Enter
String text = scanner.nextLine(); // This immediately returns empty string!

Solution:

// Solution
int number = scanner.nextInt(); // User enters "42" and presses Enter
scanner.nextLine(); // Consume the leftover newline
String text = scanner.nextLine(); // Now this waits for user input

It’s good practice to close the Scanner when you’re done with it:

scanner.close();

You can also use Scanner to read from files:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ReadFile {
public static void main(String[] args) {
try {
File file = new File("example.txt");
Scanner fileScanner = new Scanner(file);
while (fileScanner.hasNextLine()) {
String line = fileScanner.nextLine();
System.out.println(line);
}
fileScanner.close();
} catch (FileNotFoundException e) {
System.out.println("File not found");
e.printStackTrace();
}
}
}
Built with passion by Ngineer Lab