基本範例
import java.util.*;
public class InputToList {
public static void main(String[] args) {
List list = new ArrayList<>();
Scanner sc = new Scanner(System.in);
System.out.println("請輸入資料 (輸入 end 結束):");
while (sc.hasNext()) {
String input = sc.next(); // 以空白分隔
if ("end".equalsIgnoreCase(input)) break;
list.add(input);
}
System.out.println("您輸入的資料:" + list);
sc.close();
}
}
進階:逐行讀取 (保留空白)
while (sc.hasNextLine()) {
String line = sc.nextLine();
if ("end".equalsIgnoreCase(line.trim())) break;
list.add(line); // 保留整行包含空白
}
型別轉換:輸入數字存入 List
List nums = new ArrayList<>();
while (sc.hasNextInt()) {
nums.add(sc.nextInt());
}
// 遇到非整數會停止,需搭配 hasNext() 清理緩衝區
常見坑與解法
| 問題 | 原因 | 解決 |
| 無限迴圈 | 未消耗換行符 | 混用 next()/nextLine() 時,先呼叫 sc.nextLine() 清空緩衝 |
| 無法結束 | Console 無 EOF | 約定輸入 "exit" 或 Ctrl+Z (Windows) / Ctrl+D (Linux/Mac) |
| 資源洩漏 | 未關閉 Scanner | try (Scanner sc = new Scanner(System.in)) { ... } (Java 7+) |
完整可執行範例 (含 try-with-resources)
public class Demo {
public static void main(String[] args) {
try (Scanner sc = new Scanner(System.in)) {
List list = new ArrayList<>();
System.out.print("> ");
while (sc.hasNext()) {
String s = sc.next();
if ("quit".equalsIgnoreCase(s)) break;
list.add(s);
System.out.print("> ");
}
System.out.println("結果: " + list);
}
}
}