Java Scanner 类

用 Scanner 读取控制台输入、解析数字与按分隔符切分。

Beginner
Key PointsScanner 比 BufferedReader 好用但慢;nextInt 后接 nextLine 会读到残留换行,需要多调一次 nextLine。

创建 Scanner

new Scanner(System.in) reads the console, new Scanner(new File(...)) a file, new Scanner("text") a string. Call close() when done — it closes the underlying stream too.

Java
import java.util.Scanner;

public class ScannerBasic {
    public static void main(String[] args) {
        Scanner sc = new Scanner("42 hello 3.14");

        System.out.println(sc.hasNextInt());
        System.out.println(sc.nextInt());
        System.out.println(sc.next());
        System.out.println(sc.nextDouble());
        sc.close();
    }
}
Output
true
42
hello
3.14

读取不同类型

nextInt, nextDouble, nextBoolean parse by type, next reads one whitespace-delimited token and nextLine reads the rest of the line. Guard with hasNextXxx to avoid InputMismatchException.

Java
import java.util.Scanner;

public class ScannerTypes {
    public static void main(String[] args) {
        Scanner sc = new Scanner("10 20 30");

        int sum = 0;
        while (sc.hasNextInt()) {
            sum += sc.nextInt();
        }

        System.out.println(sum);
        sc.close();
    }
}
Output
60

按分隔符切分

useDelimiter(",") changes the delimiter; the default is any whitespace. Handy for CSV, but escape regex metacharacters in the delimiter.

Java
import java.util.Scanner;

public class ScannerDelim {
    public static void main(String[] args) {
        Scanner sc = new Scanner("a,b,c");
        sc.useDelimiter(",");

        while (sc.hasNext()) {
            System.out.println(sc.next());
        }
        sc.close();
    }
}
Output
a
b
c
Calling nextLine() right after nextInt() returns an empty string: nextInt leaves the newline behind. Consume it with an extra nextLine() call.

Friends & Partners