在使用 Scanner 進行控制台輸入時,若先調用 nextInt() 讀取整數,隨後調用 nextLine() 讀取字符串,會發現 nextLine() 似乎被「跳過」了,直接讀到一個空字符串,導致程序邏輯異常。
Scanner input = new Scanner(System.in);
System.out.println("請輸入航班號:");
String number = input.nextLine();
System.out.println("請輸入航班時長(分鐘):");
int length = input.nextInt(); // 讀取整數
// 此處殘留換行符
System.out.println("請輸入第二個航班號:");
String number2 = input.nextLine(); // 被跳過,讀到空串
nextInt() 只讀取數字部分,遇到換行符(\n)停止,但不會消耗該換行符。緩衝區中仍殘留換行符,後續 nextLine() 讀取時遇到換行符即刻返回,導致看似「跳過輸入」。
int length = input.nextInt();
input.nextLine(); // 消耗殘留換行符
String number2 = input.nextLine(); // 正常讀取
int length = Integer.parseInt(input.nextLine());
String number2 = input.next(); // 自動跳過空白符
Scanner 對象中,盡量避免混用 nextXxx() 與 nextLine()。nextInt()、nextDouble() 等調用後,立即補一個 nextLine() 清理緩衝區。nextLine() 讀取所有輸入,再通過 Integer.parseInt()、Double.parseDouble() 等轉換。這是 Java 初學者極易踩的坑,本質是 Scanner 的緩衝區機制導致。掌握「讀數後清換行」或「統一按行讀取」即可徹底避免。