foreach-ui logo
codeLanguages
account_treeDSA

Quick Actions

quizlock Random Quiz
trending_uplock Progress
  • 1
  • 2
  • 3
  • 4
  • quiz
Java
  • Learn how to use the Scanner class for input operations
  • Master reading different data types from console and files
  • Understand input validation and error handling with Scanner

The Scanner Class

So you want to get input from users in your Java programs. You could mess around with System.in directly, reading bytes and converting them yourself. But that's painful. That's where Scanner comes in.

Scanner lives in java.util and it's basically a smart wrapper that reads input and converts it to whatever type you need. It works with console input, files, strings, network streams, whatever. Here's the simplest version:

import java.util.Scanner;

public class BasicScanner {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        
        System.out.print("Enter your name: ");
        String name = scanner.nextLine();
        
        System.out.print("Enter your age: ");
        int age = scanner.nextInt();
        
        System.out.println("Hello, " + name + "! You are " + age + " years old.");
        
        scanner.close();
    }
}

Pretty straightforward, right? You create a Scanner, point it at System.in (the keyboard), and start reading.

Where Scanner Can Read From

You're not stuck with just keyboard input. Scanner can read from different sources:

// From the console
Scanner scanner = new Scanner(System.in);

// From a file
Scanner fileScanner = new Scanner(new File("input.txt"));

// From a string (useful for parsing)
String data = "Hello World 123";
Scanner stringScanner = new Scanner(data);

When reading from files, you'll need to handle the FileNotFoundException:

try {
    Scanner fileScanner = new Scanner(new File("input.txt"));
    // Do your reading...
    fileScanner.close();
} catch (FileNotFoundException e) {
    System.err.println("File not found: " + e.getMessage());
}

Reading Different Types

Scanner has different methods depending on what you're reading. Think of them as specialized grabbers:

Scanner scanner = new Scanner(System.in);

// Grab a whole line
String sentence = scanner.nextLine();

// Grab just one word (stops at spaces)
String word = scanner.next();

// Grab numbers
int number = scanner.nextInt();
double decimal = scanner.nextDouble();
long bigNumber = scanner.nextLong();

// Even booleans
boolean answer = scanner.nextBoolean();  // expects "true" or "false"

scanner.close();

Here's what each method actually does:

Method What It Returns What It Does
next() String Grabs the next word
nextLine() String Grabs everything until Enter
nextInt() int Grabs an integer
nextDouble() double Grabs a decimal number
nextBoolean() boolean Grabs true/false
hasNext() boolean Checks if there's more input
hasNextInt() boolean Checks if next thing is an integer

The Newline Trap (Don't Fall For This)

Here's something that trips up almost everyone when they start with Scanner. Watch what happens here:

Scanner scanner = new Scanner(System.in);

System.out.print("Enter age: ");
int age = scanner.nextInt();

System.out.print("Enter name: ");
String name = scanner.nextLine();  // Oops! This will be empty!

Why? Because nextInt() reads the number but leaves the newline character (the Enter key) sitting there. Then nextLine() immediately grabs that leftover newline and thinks it's done.

Here's the fix:

Scanner scanner = new Scanner(System.in);

System.out.print("Enter age: ");
int age = scanner.nextInt();
scanner.nextLine();  // Consume that leftover newline

System.out.print("Enter name: ");
String name = scanner.nextLine();  // Now this works correctly

Just add an extra scanner.nextLine() after reading numbers to clear out the newline. Problem solved.

Validating Input (Because Users Type Weird Stuff)

Users will type letters when you ask for numbers. They'll type "pizza" when you ask for their age. You need to check before reading:

Scanner scanner = new Scanner(System.in);

System.out.print("Enter your age: ");
if (scanner.hasNextInt()) {
    int age = scanner.nextInt();
    System.out.println("Age: " + age);
} else {
    System.out.println("That's not a number!");
}

scanner.close();

For something more robust, you can keep asking until they get it right:

Scanner scanner = new Scanner(System.in);

int age = -1;
while (age < 0) {
    System.out.print("Enter your age: ");
    if (scanner.hasNextInt()) {
        age = scanner.nextInt();
        scanner.nextLine();  // Consume newline
    } else {
        System.out.println("Please enter a valid number.");
        scanner.nextLine();  // Clear the bad input
    }
}

scanner.close();

Reading Multiple Values

Say you're building a calculator and want three numbers on one line:

Scanner scanner = new Scanner(System.in);

System.out.print("Enter three numbers: ");
int a = scanner.nextInt();
int b = scanner.nextInt();
int c = scanner.nextInt();

System.out.println("Sum: " + (a + b + c));

scanner.close();

The user types "5 10 15" and Scanner splits them up for you automatically.

Or maybe you want to keep reading numbers until the user is done:

Scanner scanner = new Scanner(System.in);
int sum = 0;
int count = 0;

System.out.println("Enter numbers (Ctrl+D to finish):");
while (scanner.hasNextInt()) {
    sum += scanner.nextInt();
    count++;
}

if (count > 0) {
    System.out.println("Average: " + (double) sum / count);
}

scanner.close();

Reading from Files

Scanners are great for reading files line by line. Much cleaner than dealing with FileInputStream directly:

try (Scanner fileScanner = new Scanner(new File("data.txt"))) {
    int lineNumber = 1;
    while (fileScanner.hasNextLine()) {
        String line = fileScanner.nextLine();
        System.out.println(lineNumber + ": " + line);
        lineNumber++;
    }
} catch (FileNotFoundException e) {
    System.err.println("File not found: " + e.getMessage());
}

Notice the try-with-resources syntax there. That's the way to go because Scanner automatically closes when you're done, even if something goes wrong.

Custom Delimiters

By default, Scanner splits on whitespace. But you can change that. Let's say you're parsing CSV data:

Scanner scanner = new Scanner("apple,banana,cherry");
scanner.useDelimiter(",");

while (scanner.hasNext()) {
    System.out.println(scanner.next());
}

scanner.close();

This works great for parsing structured data:

String data = "John Doe,25,85.5,true";
Scanner parser = new Scanner(data).useDelimiter(",");

String name = parser.next();
int age = parser.nextInt();
double score = parser.nextDouble();
boolean active = parser.nextBoolean();

parser.close();

Always Close Your Scanners

This is important. Scanners hold onto system resources. If you don't close them, you leak resources. The easiest way is try-with-resources:

try (Scanner scanner = new Scanner(System.in)) {
    // Use scanner here
}  // Automatically closed, even if there's an error

This is way better than manually calling close() and hoping nothing crashes in between.

A Few More Practical Tips

Locale matters. In some countries, decimals use commas (3,14) instead of periods (3.14). If you're reading numbers and getting weird errors, it might be a locale issue:

Scanner scanner = new Scanner(System.in).useLocale(Locale.US);

Build helper methods. If you're doing a lot of validated input, wrap it:

public int getValidInt(Scanner scanner, String prompt, int min, int max) {
    while (true) {
        System.out.print(prompt);
        if (scanner.hasNextInt()) {
            int value = scanner.nextInt();
            scanner.nextLine();
            if (value >= min && value <= max) {
                return value;
            }
            System.out.println("Must be between " + min + " and " + max);
        } else {
            System.out.println("Please enter a valid integer.");
            scanner.nextLine();
        }
    }
}

Now you can just call getValidInt(scanner, "Enter age: ", 0, 120) and know you'll get a valid number in range.

Scanner isn't perfect for everything. For high-performance file parsing, you might want BufferedReader. For complex parsing, you might want regular expressions or a proper parser. But for interactive console programs and simple file reading, Scanner is exactly what you need. It handles the tedious conversion work so you can focus on what your program actually does.

© 2026 forEach. All rights reserved.

Privacy Policy•Terms of Service