java - 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!
解决方案
我建议您在调试器中单步调试代码,看看它在做什么。
你是对的,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>
也是一个字符,通常用\n
Java 编写。
或者,由于 br 是行缓冲的,而 c 只能存储一个字符,所以输入后只传递一个字符:
缓冲意味着它将数据临时保存在内存中,直到您需要它为止。
不是br
行缓冲的,而是您的控制台。如果您要使用它来读取文件,则默认情况下它不会逐行缓冲,而是一次缓冲 8192 个字节。
不是一个明确的解决方案
这就是单步调试代码的帮助所在,您甚至可以查看 BufferedReader 中的数据。
推荐阅读
- python - 应用 SciPy 牛顿法优化熊猫数据框 Weibull 和
- android - IDE 无法识别 Android Kotlin checkBox.isChecked
- r - 在 R 中为海洋添加颜色
- nginx - 无法使用 Laravel 使用 Nginx 将图像转发到 webp
- azure-ad-b2c - 接受使用条款的 B2C 自定义政策
- firebase - 基于 Firebase 数据 Flutter 的存在导航到屏幕
- graph - 如何在不使用 Rc/RefCell 污染类型签名的情况下,在 arenas 看起来不够用时重构循环数据使用?
- jms - 如何控制 Liberty 配置文件中的模块加载顺序
- javascript - 在 PHP 中将 C 编译为 Wasm
- powershell - 使用 PowerShell 从 GitHub 拉取数据