[英]InputStreamReader, Buffered Reader, Java issue with reading standard input
[英]Testing a buffered reader reading from input stream
我在測試代碼時遇到問題。 我認為問題與使用從InputStreamReader讀取的BufferedReader有關。 我使用IntelliJ並提供以下輸入:
Hello
World!
為什么我的程序沒有打印任何東西? 這是我的代碼:
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
Deque<String> lines = new ArrayDeque<>();
String line = br.readLine();
while (line != null) {
lines.push(line);
line = br.readLine();
}
while (!lines.isEmpty()) {
System.out.println(lines.pop());
}
}
你的代碼在第一個循環中出現了問題。
要解決此問題,只需將循環條件修改為下一個:
while (line != null && !line.isEmpty()) {
lines.push(line);
line = br.readLine();
}
只需按Enter鍵,您的循環就會退出。
或者您可以添加任何其他exit code
。 例如while (line != null && !line.equals("exit"))
。 因此,當您在控制台中輸入exit code
(在上例中exit
)時,您的循環將停止,您將獲得所需的輸出。
您陷入了無限循環,因為以下條件永遠不會評估為false:
while (line != null) {
lines.push(line);
line = br.readLine();
}
您的代碼必須知道何時完成提供輸入。 在Ubuntu上我必須輸入:
Hello
World
比我確實擊中Strg + D來表示EOS 。 之后我得到了輸出:
Hello
World
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.