Java Scanner 类
用 Scanner 读取控制台输入、解析数字与按分隔符切分。
创建 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.
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();
}
}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.
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();
}
}60按分隔符切分
useDelimiter(",") changes the delimiter; the default is any whitespace. Handy for CSV, but escape regex metacharacters in the delimiter.
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();
}
}a
b
cnextLine() right after nextInt() returns an empty string: nextInt leaves the newline behind. Consume it with an extra nextLine() call.创建 Scanner
new Scanner(System.in) 读控制台,new Scanner(new File(...)) 读文件,new Scanner("文本") 读字符串。用完要 close(),它会连带关闭底层流。
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();
}
}true
42
hello
3.14读取不同类型
nextInt、nextDouble、nextBoolean 按类型解析,next 读一个以空白分隔的词,nextLine 读整行。用 hasNextXxx 先判断可以避免 InputMismatchException。
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();
}
}60按分隔符切分
useDelimiter(",") 改变分隔符,默认是任意空白。读取 CSV 这类数据时非常方便,但记得正则里的特殊字符要转义。
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();
}
}a
b
cnextInt() 之后直接 nextLine() 会读到空串 —— 因为 nextInt 没消费行尾的换行符。解决办法是在 nextInt 后再调一次 nextLine() 把它吃掉。