java.util.Scanner 是 Java 5 引入的新特性,提供簡單易用的方式從標準輸入(鍵盤)、檔案或字串獲取使用者輸入。
Scanner scanner = new Scanner(System.in); // 從鍵盤讀取
System.out.println("next方式接收:");
if (scan.hasNext()) {
String str1 = scan.next();
System.out.println("輸入的資料為:" + str1);
}
// 輸入:runoob com
// 輸出:輸入的資料為:runoob (com 被忽略)
System.out.println("nextLine方式接收:");
if (scan.hasNextLine()) {
String str2 = scan.nextLine();
System.out.println("輸入的資料為:" + str2);
}
// 輸入:runoob com
// 輸出:輸入的資料為:runoob com
| 特性 | next() | nextLine() |
|---|---|---|
| 結束符 | 空白字元 | 換行符 (Enter) |
| 空白處理 | 跳過前導空白,遇空白停止 | 保留所有空白 |
| 可讀含空格字串 | 否 | 是 |
Scanner 提供 hasNextXxx() 驗證與 nextXxx() 讀取成對方法,確保型別安全:
Scanner scan = new Scanner(System.in);
int i = 0; float f = 0.0f;
System.out.print("輸入整數:");
if (scan.hasNextInt()) {
i = scan.nextInt();
System.out.println("整數資料:" + i);
} else {
System.out.println("輸入的不是整數!");
}
System.out.print("輸入小數:");
if (scan.hasNextFloat()) {
f = scan.nextFloat();
System.out.println("小數資料:" + f);
} else {
System.out.println("輸入的不是小數!");
}
利用 hasNextDouble() 迴圈讀取,遇非數字結束:
Scanner scan = new Scanner(System.in);
double sum = 0;
int count = 0;
while (scan.hasNextDouble()) {
double x = scan.nextDouble();
count++;
sum += x;
}
System.out.println(count + "個數的和為" + sum);
System.out.println(count + "個數的平均值是" + (sum / count));
// 輸入:12 23 15 21.4 end
// 輸出:4個數的和為71.4,平均值17.85
| 方法 | 說明 |
|---|---|
hasNext() | 判斷是否還有下一個 token(預設以空白分隔) |
hasNextLine() | 判斷是否還有下一行 |
next() | 讀取下一個 token |
nextLine() | 讀取下一行 |
hasNextInt() / nextInt() | 驗證/讀取整數 |
hasNextDouble() / nextDouble() | 驗證/讀取浮點數 |
hasNextBoolean() / nextBoolean() | 驗證/讀取布林值 |
close() | 關閉 Scanner,釋放資源 |
提醒: 使用 Scanner 讀取基本型別後若需接著讀取整行字串,需額外呼叫一次 nextLine() 消耗殘留的換行符,否則會直接讀到空行。