在循環中多次 `new Scanner(System.in)` 並 `close()`,第二次讀取拋出 `NoSuchElementException`。
Scanner.close() 會關閉底層的 InputStream(即 System.in)。System.in 是進程級單例,關閉後無法重新打開,後續任何讀取操作均會失敗。while (true) {
Scanner s = new Scanner(System.in);
int x = s.nextInt();
s.close(); // 錯誤:關閉了 System.in
}
Scanner scanner = new Scanner(System.in);
while (running) {
int x = scanner.nextInt();
// ...
}
// 程式結束前關閉
scanner.close();
若必須分離邏輯,可傳遞 Scanner 實例,或使用 BufferedReader 包裝 System.in(同樣不可關閉底層流)。
對於 System.in、System.out 等標準流,JVM 退出時自動回收,業務代碼通常不需要顯式關閉。
i4、j9 疑為 i > 4、j > 9 的轉義錯誤,需修正邊界判斷。OutIndexOfException 建議繼承 RuntimeException 簡化處理。