java.util.Scanner 是 Java 5 引入的強大掃描工具,支援從控制台、文件、字符串、輸入流等多種來源解析基本類型與字符串。
Scanner s = new Scanner(System.in);
String str = s.next(); // 讀取下一個 token(空格分隔)
int i = s.nextInt(); // 讀取整數
double d = s.nextDouble(); // 讀取浮點數
System.out.println(str + i + d);
Scanner reader = new Scanner(System.in);
System.out.println("請輸入一個整數:");
long a = reader.nextLong();
String result = (a % 2 == 0) ? "偶數" : "奇數";
System.out.println("結果是:" + result);
Scanner s = new Scanner(System.in);
while (true) {
String line = s.nextLine();
if (line.equals("exit")) break;
System.out.println(">>>" + line);
}
Scanner 支援豐富的輸入來源:
new Scanner(System.in) - 標準輸入new Scanner(new File("data.txt")) - 文件new Scanner("1 fish 2 fish") - 字符串new Scanner(inputStream) - 輸入流// 使用正則分隔符
Scanner s = new Scanner("1 fish 2 fish red fish blue fish")
.useDelimiter("\\s*fish\\s*");
System.out.println(s.nextInt()); // 1
System.out.println(s.nextInt()); // 2
System.out.println(s.next()); // red
System.out.println(s.next()); // blue
// 正則分組匹配
Scanner s2 = new Scanner("1 fish 2 fish red fish blue fish");
s2.findInLine("(\\d+) fish (\\d+) fish (\\w+) fish (\\w+)");
MatchResult r = s2.match();
for (int i = 1; i <= r.groupCount(); i++) {
System.out.println(r.group(i));
}
| 方法 | 說明 |
|---|---|
hasNext() | 是否有下一個 token |
hasNextLine() | 是否有下一行 |
next() | 獲取下一個 token |
nextLine() | 獲取下一行 |
useDelimiter(Pattern) | 設定分隔符 |
delimiter() | 獲取當前分隔符 Pattern |
close() | 關閉掃描器 |
Scanner s = new Scanner(new FileInputStream("AutoSubmit.java"));
while (s.hasNextLine()) {
System.out.println(s.nextLine());
}
s.close();
Scanner 實作了 Iterator 介面,配合正則表達式極靈活,但 API 眾多且文檔部分晦澀,實務上掌握核心方法即可應付大多數場景。