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
'\r' is the representation of the special character CR (carriage return), it moves the cursor to the beginning of the line. '\n'(line feed) moves the cursor to the next line . On windows both are combined as \r\n to indicate an end of line (ie, move the cursor to the beginning of the next line).
The Line Feed (LF) character moves the cursor down to the next line without returning to the beginning of the line. This character is used as the new line character in Unix based systems (Linux, macOS X, Android, etc). Codes Display. ASCII Decimal. Hex.
Line Break: A line break (“\n”) is a single character that defines the line change. In order to replace all line breaks from strings replace() function can be used.
The enter key's ascii value is 0a ,meaning newline ,it is different from Carriage Return (13 or 0d in ascii).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With