Java 11 中的 BufferedReader 有一個不尋常的問題。我有一個簡單的命令列學生跟蹤器應用程式,它從 讀取輸入System.in,將其轉換為適當的Command介面實作,然后執行它。
void execute() {
System.out.println("Learning Progress Tracker");
try (reader) { // reader is new BufferedReader(new InputStreamReader(System.in))
String line;
while (!shutdown) {
line = reader.readLine();
Command command = Command.stringToCommand(line);
if (command instanceof ExitCommand) {
shutdown = true;
}
command.execute(reader, db);
}
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
有些命令只是簡單地處理輸入并將輸出列印到System.out,有些則繼續使用reader以接收額外的輸入。例如,AddStudentsCommand像這樣實作執行:
public void execute(BufferedReader reader, Database db) {
String line;
String[] credentials;
int numAdded = 0;
prompt(); // Prints prompt to System.in to enter credentials
try {
while (!(line = reader.readLine()).equals("back")) {
// process input
}
}
}
這是奇怪的部分。在while (!(line = reader.readLine()).equals("back")) {line 評估為 true 之后,reader's 的緩沖區最終會\n在其緩沖區中領先,然后是我輸入的任何內容,這會導致 toreadLine()啟動兩次。prompt()更奇怪的是,只有當我System.out.println()在readLine(). 如果在閱讀之前列印了某些文本,則緩沖區行為正確并且不會顯示System.out前導。\n我錄制了一個小視頻來說明我的意思:https ://www.youtube.com/watch?v=H7PBr6Qpykg 。
我不知道自己做錯了什么,也不明白那個討厭的錯誤是從哪里來的。任何人都可以復制嗎?
uj5u.com熱心網友回復:
僅當您在 IDE 中運行程式時才會出現此問題。如果您從命令列運行它,使用 command java [ClassName],它應該可以正常作業。
問題是IntelliJ IDEA中的一個錯誤,該錯誤已在 2022.1.2 版本中修復,因此您可能需要升級。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/496065.html
上一篇:如何使用命令讓機器人dm我
