int a = System.in.read(); // 讀取單個字符的 ASCII 值
// 輸入 "123" 只讀取 '1' → 返回 49 (ASCII 碼)
// 輸入 "abc" 只讀取 'a' → 返回 97
結論:System.in.read() 只能讀取單字節,絕不適用於 讀取數字或字符串。
import java.util.Scanner;
public class ConsoleInputDemo {
public static void main(String[] args) {
try (Scanner scanner = new Scanner(System.in)) {
// 讀取整數
System.out.print("請輸入整數:");
int number = scanner.nextInt();
// 讀取浮點數
System.out.print("請輸入小數:");
double decimal = scanner.nextDouble();
// 關鍵:消耗換行符
scanner.nextLine();
// 讀取整行字符串(含空格)
System.out.print("請輸入字符串:");
String text = scanner.nextLine();
// 讀取單個詞(以空白分隔)
System.out.print("請輸入單詞:");
String word = scanner.next();
System.out.printf("整數:%d,小數:%.2f,字符串:%s,單詞:%s%n",
number, decimal, text, word);
}
}
}
| 方法 | 行為 | 適用場景 |
|---|---|---|
nextInt() | 解析整數,停留在分隔符前 | 菜單選項、數量輸入 |
nextDouble() | 解析浮點數 | 價格、測量數據 |
next() | 讀取下一個詞(空白分隔) | 單詞、命令參數 |
nextLine() | 讀取整行(含空格,至換行符) | 地址、描述、完整句子 |
// 錯誤示範
int age = scanner.nextInt();
String name = scanner.nextLine(); // 讀到空字符串!因為換行符未被消耗
// 正確做法
int age = scanner.nextInt();
scanner.nextLine(); // 關鍵:消耗殘留的換行符
String name = scanner.nextLine();
public static int readValidInt(Scanner scanner, String prompt) {
while (true) {
System.out.print(prompt);
if (scanner.hasNextInt()) {
int value = scanner.nextInt();
scanner.nextLine(); // 清理換行
return value;
} else {
System.out.println("輸入無效,請輸入整數!");
scanner.nextLine(); // 丟棄無效輸入
}
}
}
System.in.read(),它只適合底層字節流處理Scanner,功能全面且異常處理簡單hasNextXxx() 進行輸入預檢,提升程序健壯性