What is Scanner in Java? Give Examples

The Scanner class in Java provides a way to read user input from console or files.

It can be used to read different data types, including strings, integers, and floating-point numbers.

Here are some examples of how to use the Scanner class:

Reading a String from the Console

import java.util.Scanner;

public class ScannerExample {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter a string: ");
        String input = scanner.nextLine();
        System.out.println("You entered: " + input);
        scanner.close();
    }
}

In this example, we create a new Scanner object and pass in System.in as the input source. We then prompt the user to enter a string, and use the nextLine() method to read the string from the console. Finally, we print out the user’s input using the System.out.println().

Reading an Integer from the Console

import java.util.Scanner;

public class ScannerExample {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter an integer: ");
        int input = scanner.nextInt();
        System.out.println("You entered: " + input);
        scanner.close();
    }
}

In this example, we use the Scanner.nextInt() method to read an integer from the console.

Note that we did not need to use the nextLine() method to consume the newline character after reading the integer, as we did in the previous example.

Reading a File

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

public class ScannerExample {
    public static void main(String[] args) {
        try {
            File file = new File("input.txt");
            Scanner scanner = new Scanner(file);
            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
                System.out.println(line);
            }
            scanner.close();
        } catch (FileNotFoundException e) {
            System.out.println("File not found: " + e.getMessage());
        }
    }
}

In this example, we create a new Scanner object and pass in a File object as the input source. We then use a while loop to read each line of the file using the hasNextLine() and nextLine() methods of the Scanner class.

Scanner Alternatives

While java.util.Scanner is a useful class for simple input scenarios, there are newer and better alternatives available for more complex reading input. Scanner has some limitations and performance issues that can become problematic for more complex input scenarios.

Some of the newer and better alternatives to Scanner include:

BufferedReader

BufferedReader is a more efficient and versatile way to read input from the console or from files. It is often used to read large files or to read input that requires advanced parsing or filtering.

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class BufferedReaderExample {
    public static void main(String[] args) {
        try {
            BufferedReader reader = new BufferedReader(new FileReader("input.txt"));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
            reader.close();
        } catch (IOException e) {
            System.out.println("Error reading file: " + e.getMessage());
        }
    }
}

Console

Console provides a more flexible way to read console input. It is available since Java 6 and offers methods for reading passwords and formatted input. It can throw unchecked exceptions (like Scanner.)

Here’s an example of how to use Console to read a password:

import java.io.Console;

public class ConsoleExample {
    public static void main(String[] args) {
        Console console = System.console();
        if (console == null) {
            System.out.println("Console not available");
            System.exit(1);
        }

        char[] password = console.readPassword("Enter password: ");
        System.out.println("You entered: " + new String(password));
    }
}

JLine

JLine is an open source Java library for handling console input. It provides advanced console input features like history, tab completion, and multi-line editing.

Speak Your Mind