Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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 , enter image description here Since, expected output is blank, it means my codes still expects \n or \r which is not provided by input

like image 441
Pradeep Avatar asked Oct 05 '13 06:10

Pradeep


People also ask

What does \r do in Java?

'\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).

What is a linefeed character?

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.

How do you stop a line break in Java?

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.

Is Enter carriage return or new line?

The enter key's ascii value is 0a ,meaning newline ,it is different from Carriage Return (13 or 0d in ascii).


2 Answers

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.

like image 114
Jon Skeet Avatar answered Nov 02 '22 23:11

Jon Skeet


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.

like image 31
Heshitha Hettihewa Avatar answered Nov 03 '22 01:11

Heshitha Hettihewa