輸入 3 後,控制台連續輸出兩條 System.out 語句,預期僅一條。
Scanner.nextLine() 讀取**整行**(含結尾換行符),但若前一次輸入用 nextInt(),緩衝區殘留 \n,導致 nextLine() 直接讀到空行。switch,匹配 default 或其他分支,產生額外輸出。
// 方案 1:統一用 next() 讀單詞(自動跳過空白符)
String input = sc.next();
// 方案 2:nextInt() 後補一個 nextLine() 吞掉換行符
int c1 = sc.nextInt();
sc.nextLine(); // 吞掉換行符
String loginUser = sc.nextLine();
next()** 讀取選項字符/字符串,避免換行符陷阱。nextLine() 清空緩衝區,再正式讀取。一行 sc.next() 替換 sc.nextLine(),瞬間解決 switch 多重輸出之謎。