Java Scanner Class


In Java, capturing user input is a critical part of interactive applications. One of the most popular ways to handle input is by using the Scanner class, which is part of the java.util package. The Scanner class makes it easy to parse and read data from various input sources, such as keyboard input, files, and streams.


What is the Java Scanner Class?

The Scanner class in Java is used to read input from different sources such as keyboard input, files, and other data streams. It simplifies the task of parsing and tokenizing input, allowing developers to read various data types such as integers, floats, strings, and more.

Key Features of the Scanner Class:

  • It provides methods for reading different types of data (like int, float, String, etc.).
  • It supports input validation and parsing of regular expressions.
  • It can read data from multiple sources such as System.in (keyboard), files, and strings.
  • It provides methods to skip unwanted tokens and delimiters.

How to Use the Java Scanner Class

Importing the Scanner Class

To use the Scanner class, you need to import it from the java.util package:

import java.util.Scanner;

Commonly Used Methods of the Scanner Class

The Scanner class provides several methods to read different types of input. Here are some of the most commonly used methods:

Method Description
next() Reads the next token as a string.
nextInt() Reads the next token as an integer.
nextDouble() Reads the next token as a double.
nextLine() Reads the entire line as a string.
hasNext() Returns true if there is another token.
hasNextInt() Returns true if the next token is an integer.
hasNextDouble() Returns true if the next token is a double.

Example 1: Reading Strings from the User

You can use the next() or nextLine() method to read strings from the user. The difference is that next() reads a single word, while nextLine() reads the entire line.

Code Example:

import java.util.Scanner;

public class ScannerExample {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        // Reading a single word
        System.out.print("Enter a word: ");
        String word = scanner.next();
        System.out.println("You entered: " + word);

        // Reading a full line
        System.out.print("Enter a sentence: ");
        scanner.nextLine();  // Consume the newline character
        String sentence = scanner.nextLine();
        System.out.println("You entered: " + sentence);

        scanner.close();
    }
}

Explanation:

  • next() reads the first token (word) until a space is encountered.
  • nextLine() reads the entire line of text, including spaces.

Example 2: Reading Different Data Types (Integer, Double)

You can use methods like nextInt() and nextDouble() to read numbers from the user.

Code Example:

import java.util.Scanner;

public class ScannerExample {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        // Reading an integer
        System.out.print("Enter an integer: ");
        int num = scanner.nextInt();
        System.out.println("You entered: " + num);

        // Reading a double
        System.out.print("Enter a decimal number: ");
        double decimal = scanner.nextDouble();
        System.out.println("You entered: " + decimal);

        scanner.close();
    }
}

Explanation:

  • nextInt() reads an integer value from the user.
  • nextDouble() reads a decimal (double) value from the user.

Example 3: Handling Mixed Input (String and Number)

Sometimes, you may want to read both strings and numbers in a mixed format. You can use the nextLine() method after reading a number to handle this case.

Code Example:

import java.util.Scanner;

public class ScannerExample {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        // Reading an integer
        System.out.print("Enter your age: ");
        int age = scanner.nextInt();

        // Consume the remaining newline character after nextInt()
        scanner.nextLine();

        // Reading a string (name)
        System.out.print("Enter your name: ");
        String name = scanner.nextLine();

        System.out.println("Hello " + name + ", you are " + age + " years old.");

        scanner.close();
    }
}

Explanation:

  • After reading the integer input with nextInt(), a nextLine() call is needed to consume the newline character left by nextInt(). This ensures that the next nextLine() correctly reads the entire string.

Example 4: Checking for Valid Input (hasNextInt, hasNextDouble)

Sometimes, you may need to validate whether the user entered a valid input type, such as checking if the next token is an integer or a double. The hasNextInt() and hasNextDouble() methods come in handy here.

Code Example:

import java.util.Scanner;

public class ScannerExample {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        // Checking if the next input is an integer
        System.out.print("Enter a number: ");
        if (scanner.hasNextInt()) {
            int num = scanner.nextInt();
            System.out.println("You entered: " + num);
        } else {
            System.out.println("That's not a valid number!");
        }

        scanner.close();
    }
}

Explanation:

  • hasNextInt() checks if the next token can be interpreted as an integer. If it is, you can safely use nextInt() to read it.

Handling File Input with Scanner

The Scanner class can also be used to read data from files. To do so, you need to pass a File object or FileInputStream to the Scanner constructor.

Code Example:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class FileInputExample {
    public static void main(String[] args) {
        try {
            // Create a Scanner to read from a file
            File file = new File("input.txt");
            Scanner fileScanner = new Scanner(file);

            // Reading each line from the file
            while (fileScanner.hasNextLine()) {
                String line = fileScanner.nextLine();
                System.out.println(line);
            }

            fileScanner.close();
        } catch (FileNotFoundException e) {
            System.out.println("File not found.");
        }
    }
}

Explanation:

  • The Scanner object is created using a File object, allowing you to read from the file line by line using nextLine().

Best Practices for Using the Scanner Class

  1. Close the Scanner: Always close the Scanner object when you’re done with it using scanner.close(). This is particularly important when reading from files or streams to free up resources.

  2. Use nextLine() to Read Full Lines: When reading input that may contain spaces, use nextLine() to capture the full line of text.

  3. Input Validation: Use hasNext() methods (e.g., hasNextInt(), hasNextDouble()) to check if the input matches the expected type before trying to read it.

  4. Handle Input Mismatch Exceptions: Be prepared to handle InputMismatchException if the input type doesn’t match the expected one. You can catch this exception to provide meaningful feedback to the user.