简体   繁体   English

如何在java中读取不以新行或回车字符结尾的行?

[英]How to read a line which doesn't end with new line or carriage return character in java?

I am using BufferedReader as follows, 我正在使用BufferedReader,如下所示,

BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
for (int i = 0; i < 4; i++) {
   System.out.println(stdin.readLine());
}

And the input given is as follows, 输入的内容如下,

1
2
3

The last input doesn't end with \\n or \\r , therefore for 3 readLine() will expect input from user unless user presses enter key 最后一个输入不以\\n\\r结尾,因此对于3 readLine()将期望来自用户的输入,除非用户按下回车键

Any solution for this using Scanner ? 使用Scanner的任何解决方案?

Actually, I got into this problem while solving , Quora Question Nearby , In their conditions they have mentioned following lines, 实际上,我在解决问题时遇到了这个问题, Quora Question Nearby ,在他们的条件下他们提到了以下几行,

Does the last line in the input test case end with a newline? 输入测试用例中的最后一行是否以换行符结尾? [link] [链接]

Nope. 不。 No trailing spaces or newlines. 没有尾随空格或换行符。


Link for Code , Submitted at above page, test cases are failing 代码链接 ,在上面提交,测试用例失败

For Test Case Zero, It shows following output , 对于测试用例零,它显示以下输出, 在此输入图像描述 Since, expected output is blank, it means my codes still expects \\n or \\r which is not provided by input 由于预期的输出是空白的,这意味着我的代码仍然需要\\n or \\r ,它不是由输入提供的

If the input is terminated - which would be the case if standard input is actually being redirected from a file, for example - then it's fine. 如果输入被终止 - 例如,如果标准输入实际上是从文件重定向的话就是这种情况 - 那么它就没问题了。 BufferedReader.readLine will still return the last line from its input, when it detects the end of the underlying data. BufferedReader.readLine检测到基础数据的结束时,它仍将从其输入返回最后一行。

Given that this is an automated challenge, I would expect this to be the case - I'd expect it to be run as something like 鉴于这是一个自动化的挑战,我希望情况就是这样 - 我希望它可以运行

java Solution < input.txt

So basically, I believe you should be fine. 所以基本上,我相信你应该没事。

If you want to get the output without pressing enter,it is impossible. 如果你想在没有按下输入的情况下获得输出,那是不可能的。 Because System.in stream doesn't allow you to take input without pressing enter by default.You have to use a third party library like JNI for that. 因为System.in流不允许您输入输入而不按默认输入。您必须使用第三方库,如JNI

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM