java.util.Scanner 是 JDK 1.5 引入的簡單文本掃描器,可從標準輸入、文件、字符串解析基本類型與字符串。
Scanner in = new Scanner(System.in);
System.out.print("請輸入姓名:");
String name = in.nextLine(); // 讀取整行(含空格)
System.out.print("請輸入年齡:");
int age = in.nextInt(); // 讀取 int
System.out.print("請輸入身高:");
double height = in.nextDouble(); // 讀取 double
in.close(); // 釋放資源
Java 中 + 既是數學加法,也是字符串連接,**運算順序從左到右**,遇到字符串即轉為連接模式:
System.out.println("2+3=" + 5); // "2+3=5" ✅
System.out.println("2+3=" + 2 + 3); // "2+3=23" ❌ 預期 "2+3=5"
System.out.println("2+3=" + (2 + 3)); // "2+3=5" ✅ 括號優先計算
System.out.println(2 + 3 + "=2+3=" + (2 + 3)); // "5=2+3=5" ✅
| 場景 | 問題 | 解決方案 |
|---|---|---|
| nextInt() 後調用 nextLine() | 讀到空行(換行符未被消費) | 次數調用一次 in.nextLine() 吃掉換行符,或統一用 nextLine() 再 Integer.parseInt() |
| 輸入非數字導致 InputMismatchException | 程序崩潰 | hasNextInt() 校驗,或 try-catch 循環重輸 |
| 字符串拼接在循環中 | 產生大量臨時 StringBuilder 對象,性能差 | 手動使用 StringBuilder / StringJoiner (Java 8+) |
| Scanner 未關閉 | 資源洩漏 | try-with-resources: try (Scanner in = new Scanner(System.in)) { ... } |
五、總結
Scanner 適合簡單控制台交互、文本解析;高性能場景(大文件、高併發)請使用
BufferedReader+ 手動解析或成熟 CSV/JSON 庫。牢記+拼接優先級與換行符陷阱,是寫出健壯輸入代碼的關鍵。