简体   繁体   中英

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 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

Any solution for this using Scanner ?

Actually, I got into this problem while solving , Quora Question Nearby , In their conditions they have mentioned following lines,

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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