java.util.Scanner 是 Java 基礎輸入最常用的工具,但 next()、nextLine()、nextInt()、hasNextInt() 的行為差異常導致新手困惑。本文透過圖解與範例徹底釐清。
| 方法 | 讀取範圍 | 分隔符處理 | 游標位置 | 典型用途 |
|---|---|---|---|---|
| next() | 下一個 token(預設空白分隔) | 跳過前導分隔符,讀取到下一個分隔符不包含分隔符 | 停在分隔符前 | 讀取單字、字串 token |
| nextLine() | 整行(含空白) | 讀取到 換行符 \n,包含換行符並丟棄 | 移到下一行開頭 | 讀取整行文字、含空格字串 |
| nextInt() | 下一個 token → 解析為 int | 同 next(),再嘗試轉型 | 同 next() | 直接讀取整數 |
| hasNextInt() | 檢視下一個 token 是否可解析為 int | 不移動游標 | 不變 | 輸入驗證、避免異常 |
"a b c\n"呼叫順序 回傳值 游標位置(^) -------------------------------------------------- next() "a" ^ b c\n next() "b" ^ c\n nextLine() " c" ^\n (下一行開頭)
Scanner sc = new Scanner(System.in);
int age = sc.nextInt(); // 輸入 "25\n",讀取 25,游標停在 \n 前
String name = sc.nextLine(); // 直接讀到 \n → 回傳空字串 ""!
解法:在 nextInt() 後呼叫一次 sc.nextLine() 吃掉殘留換行符,或統一使用 nextLine() 再自行 Integer.parseInt()。
import java.util.Scanner;
public class SumThree {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("請輸入三個整數(空白或換行分隔):");
int a = 0, b = 0, c = 0;
if (input.hasNextInt()) a = input.nextInt();
if (input.hasNextInt()) b = input.nextInt();
if (input.hasNextInt()) c = input.nextInt();
System.out.println("總和 = " + (a + b + c));
input.close();
}
}
sc.useDelimiter(",") 以逗號分隔 token。sc.useDelimiter("\\s*,\\s*") 支援逗號前後可有空白。try-with-resources 自動關閉:try (Scanner sc = new Scanner(System.in)) { ... }。