What does “scanner” mean in Java?

In Java, `Scanner` is a class used to read data from standard input, files, or other input streams. It provides convenient methods for parsing and retrieving values from user input or other data sources.

Using the `Scanner` class allows for the splitting of data in input streams into different tokens, such as integers, floating-point numbers, strings, etc., and extracting specific values from these tokens. The `Scanner` class offers various methods for reading different types of data, like `nextInt()`, `nextDouble()`, `nextLine()`, etc.

Here are some common usages of the `Scanner` class:

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in); // 从标准输入读取数据

        System.out.print("请输入一个整数:");

        int num = scanner.nextInt(); // 读取整数

        System.out.println("您输入的整数是:" + num);

        System.out.print("请输入一个浮点数:");

        double decimal = scanner.nextDouble(); // 读取浮点数

        System.out.println("您输入的浮点数是:" + decimal);

        System.out.print("请输入一行文本:");

        String text = scanner.nextLine(); // 读取一行文本

        System.out.println("您输入的文本是:" + text);

        scanner.close(); // 关闭Scanner对象

    }

}

By creating a `Scanner` object and specifying the input stream, you can read different types of data from the console or any other input source. This class is a commonly used utility class in the Java standard library, and can be used for interactive input, file parsing, and other scenarios.

bannerAds