使用BufferedReader读取所有行 [英] Read all lines with BufferedReader
问题描述
我想使用BufferedReader在控制台中输入多行文本,当我点击Enter以查找整个文本长度的总和时。问题是,我似乎进入了无限循环,当我按下Enter时,程序没有结束。我的代码如下:
I want to type a multiple line text into the console using a BufferedReader and when I hit "Enter" to find the sum of the length of the whole text. The problem is that it seems I'm getting into an infinite loop and when I press "Enter" the program does not come to an end. My code is below:
InputStreamReader instream = new InputStreamReader(System.in);
BufferedReader buffer = new BufferedReader(instream);
line= buffer.readLine();
while (line!=null){
length = length + line.length();
line= buffer.readLine();
}
你能告诉我我做错了吗?
Could you please tell me what I'm doing wrong?
推荐答案
读取所有行的惯用方法是 while((line = buffer.readLine())!=空)
。另外,我建议 试用资源
声明。类似
The idiomatic way to read all of the lines is while ((line = buffer.readLine()) != null)
. Also, I would suggest a try-with-resources
statement. Something like
try (InputStreamReader instream = new InputStreamReader(System.in);
BufferedReader buffer = new BufferedReader(instream)) {
long length = 0;
String line;
while ((line = buffer.readLine()) != null) {
length += line.length();
}
System.out.println("Read length: " + length);
} catch (Exception e) {
e.printStackTrace();
}
如果要在收到空行时结束循环,请添加测试,而
循环
If you want to end the loop when you receive an empty line, add a test for that in the while
loop
while ((line = buffer.readLine()) != null) {
if (line.isEmpty()) {
break;
}
length += line.length();
}
A
break
语句将控制转移到封闭语句之外。
A
break
statement transfers control out of an enclosing statement.
这篇关于使用BufferedReader读取所有行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!