控制台執行 Java 程式時,使用者鍵盤輸入的字元會即時回顯在終端機 (即圖中綠色部分)。若不想看到輸入回顯,有三種常見替代方案:
// 輸入資料預先存放 input.txt
Scanner scanner = new Scanner(new File("input.txt"));
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
// 處理 line
}
scanner.close();
Console console = System.console();
if (console != null) {
char[] password = console.readPassword("請輸入: "); // 不回顯
// 處理 password,用畢建議清零: Arrays.fill(password, ' ');
} else {
// IDE 內建終端機通常回傳 null
System.err.println("請在命令列執行或改用檔案輸入");
}
// Swing
String input = JOptionPane.showInputDialog(null, "請輸入:", "輸入", JOptionPane.QUESTION_MESSAGE);
// JavaFX (需模組化專案)
TextInputDialog dialog = new TextInputDialog();
dialog.setHeaderText("請輸入");
Optional<String> result = dialog.showAndWait();
截圖顯示為 IDE (IntelliJ/Eclipse) 內建控制台,綠色字為使用者輸入。最直接做法:**在 Run Configuration 中設定「Input file」導向準備好的測資檔案**,或直接修改程式碼改用 `new Scanner(new File("..."))`。若作業要求互動式輸入但不想回顯,只能在外部 `cmd`/`bash` 執行並搭配 `Console.readPassword`。
區分「控制台回顯」與「程式邏輯」兩個層面,選擇最適合當前開發階段的方案。