首页 > 解决方案 > How exactly are characters stored and passed in BufferedReader involving iterations?

问题描述

The title might look too general, but here it is. I found this code:

//class, main, etc.
char c;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter e to exit!");

do
{
    c=(char)br.read();
    System.out.println(c);
}while(c!='q');

/*Example output:
  12ae
  1
  2
  a
  e */
  //Where I type 12ae and press enter initially

How exactly is the output achieved, when println() is called every time when c is assigned a value, and char can store only one character?

Shouldn't it be either(by my understanding): In the first iteration, 1 is passed to c, println(c) is called, Second iteration begins, 2 is passed and so on,

giving an output: 1 1 2 2 a a e e (Where first occurrence is my input after I press enter, second is the output with newline due to the property of println)

Or, since br is line buffered, but c can only store one character, only one character is passed after the input is entered:

In which case output would be: 12ae e

IN A NUTSHELL: How is multiple data(12ae) passed at once(after I hit enter, after typing) to println repeatedly?

I'm really confused, and have looked online, where I find the usual generic definitions(pun intended) but not a clear solution. Thanks!

标签: javacharinputstreambufferedreaderbufferedinputstream

解决方案


我建议您在调试器中单步调试代码,看看它在做什么。

你是对的,c一次只有一个值。

如果您有1 1 2 2 a a e e输入,则为 15 个字符,包括空格。

在你输入

12ae<enter>
1<enter>
2<enter>
a<enter>
e<enter>
q

这将打印

1
2
a
e

1

2

a

e

as<enter>也是一个字符,通常用\nJava 编写。

或者,由于 br 是行缓冲的,而 c 只能存储一个字符,所以输入后只传递一个字符:

缓冲意味着它将数据临时保存在内存中,直到您需要它为止。

不是br行缓冲的,而是您的控制台。如果您要使用它来读取文件,则默认情况下它不会逐行缓冲,而是一次缓冲 8192 个字节。

不是一个明确的解决方案

这就是单步调试代码的帮助所在,您甚至可以查看 BufferedReader 中的数据。


推荐阅读