Scanner in = new Scanner(System.in);
String[] input = new String[26];
for (int i = 0; input[i] != "end"; i++) { // ❌ 錯誤:字符串用 != 比較引用
input[i] = in.next();
}
in.close();
三大致命問題:
input[i] != "end":字符串**必須用 .equals() 比較內容**,!= 比較對象引用,字面量 "end" 與 in.next() 返回的新對象引用永不相等 → 死循環。for 循環先判斷條件再執行體:i=0 時 input[0] 為 null,null != "end" 為 true 進入循環,但隨後 in.next() 讀取第一個詞,而非預期的「先讀再判」。in.next() 按**空白符分詞**,而非按行讀取。輸入 "this is line" 會被拆成 3 次循環。Scanner in = new Scanner(System.in);
List<String> lines = new ArrayList<>(); // 動態列表優於固定數組
String line;
do {
line = in.nextLine(); // 按行讀取,保留空格
if (!"end".equals(line)) { // 防空指針,常量在前
lines.add(line);
}
} while (!"end".equals(line));
in.close();
// lines 現在包含除 "end" 外的所有行
System.out.println("共讀取 " + lines.size() + " 行");
| 方法 | 分隔符 | 返回值 | 適用場景 |
|---|---|---|---|
next() | 空白符 (空格/換行/Tab) | 單詞 | 解析命令參數、數字序列 |
nextLine() | 換行符 \n/\r\n | 整行 (含空格) | 讀取文本行、用戶輸入句子 |
nextInt() 等 | 空白符 | 基本類型 | 直接讀數字,需配合 nextLine() 清理換行符 |
標準 Scanner 無超時機制。若需「5 秒無輸入自動繼續」:
ExecutorService es = Executors.newSingleThreadExecutor();
Future<String> future = es.submit(() -> {
Scanner s = new Scanner(System.in);
return s.nextLine();
});
try {
String line = future.get(5, TimeUnit.SECONDS);
// 處理輸入
} catch (TimeoutException e) {
future.cancel(true);
System.out.println("輸入超時");
} finally {
es.shutdownNow();
}
.equals()**,常量寫前防 NPE:"end".equals(input)。nextLine(),按詞用 next()。List + do-while,避免數組越界與邏輯倒置。