針對競技程式設計、CLI 工具、批次處理,Scanner 與 BufferedReader 是最常用的輸入工具。
import java.util.Scanner;
public class ScannerInputDemo {
public static void main(String[] args) {
@SuppressWarnings("resource")
Scanner sc = new Scanner(System.in);
// 讀取整數
System.out.print("輸入整數 n: ");
int n = sc.nextInt();
// 讀取字串 (以空白分隔)
System.out.print("輸入字串: ");
String s = sc.next();
// 讀取整行 (含空白)
System.out.print("輸入整行: ");
sc.nextLine(); // 消耗換行符
String line = sc.nextLine();
System.out.println("n=" + n + ", s=" + s + ", line=" + line);
}
}
import java.io.*;
import java.util.Scanner;
public class ScannerFileSum {
public static void main(String[] args) throws IOException {
// 建立測試檔案
try (FileWriter fw = new FileWriter("num.txt")) {
fw.write("2 2.2 3.3 3.33 4.5 done");
}
// 掃描求和
double sum = 0;
try (Scanner sc = new Scanner(new File("num.txt"))) {
while (sc.hasNext()) {
if (sc.hasNextDouble()) {
sum += sc.nextDouble();
} else {
String token = sc.next();
if ("done".equals(token)) break;
else throw new RuntimeException("格式錯誤: " + token);
}
}
}
System.out.println("Sum = " + sum); // 15.33
}
}
import java.io.*;
public class BufferedReaderDemo {
public static void main(String[] args) {
try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) {
System.out.print("輸入一行文字: ");
String line = br.readLine(); // 阻塞直到換行
System.out.println("您輸入: " + line);
} catch (IOException e) {
e.printStackTrace();
}
}
}
try (BufferedReader br = new BufferedReader(new FileReader("data.txt"))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
}
| 維度 | Scanner | BufferedReader |
|---|---|---|
| 讀取速度 (大量資料) | 較慢 (解析開銷) | 極快 (單純緩衝) |
| 型別自動解析 | 支援 (nextInt, nextDouble...) | 不支援 (需手動 parse) |
| 正則分隔符 | 支援 useDelimiter() | 不支援 |
| 記憶體佔用 | 略高 | 極低 |
| 適用場景 | 互動式輸入、混合型別、檔案解析 | 大檔案逐行、高效能需求、競技程式 |
// 快速輸入模板 (BufferedReader + StringTokenizer)
import java.io.*;
import java.util.*;
public class FastInput {
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static StringTokenizer st;
static String next() throws IOException {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(br.readLine());
}
return st.nextToken();
}
static int nextInt() throws IOException { return Integer.parseInt(next()); }
static long nextLong() throws IOException { return Long.parseLong(next()); }
static double nextDouble() throws IOException { return Double.parseDouble(next()); }
public static void main(String[] args) throws IOException {
int n = nextInt();
long sum = 0;
for (int i = 0; i < n; i++) sum += nextLong();
System.out.println(sum);
}
}
BufferedReader + StringTokenizer 或 Java 8+ Stream 處理。Scanner 開發效率最高。Scanner 針對結構化文字;BufferedReader 針對行導向日誌。try-with-resources (JDK 7+) 自動關閉資源。