I am reading several lines from the console in a java program using the readLine command from the BufferedReader class. However, the program pauses at the end of the last line and does not proceed until i press return. How do I eliminate this pause?
What exactly do you do and what do you expect? I have two guesses:
- You're having a superfluous
readLine()
at the end of the program. Remove it or change loop conditions appropriately to solve this. - You expect the program to start work on a line that is being entered (without hitting Return at the end). That's where your expectations are dead-wrong.
readLine()
returns a full line and blocks while it is being entered. So the call just waits until you hit Return and then returns the line you just entered. To get input while the user is typing neitherBufferedReader
norreadLine()
are very suitable.
It's a catch-22; you cannot know it's the last line, until it's been fully entered (including the carriage return at the end) and you can parse it. So you only know that you could have skipped waiting once you've already missed your chance.
That assumes, of course, that you detect the last line based on its content (e.g. empty string, specific "42" string, etc.). If you have some other means of detecting what the last line is, then you can use this as your while loop condition - hence you don't need to wait to read the "sentinel" line that simply tells you to exit.
But in the code example you posted, you only get access to the "42" line after it has been completely entered - including some line terminator (carriage return, EOF, etc.). Thus until you hit return, that line doesn't exist from the reader's perspective.
A line is a CR or CRLF terminiated sequence of characters. And readline() just does what it's name says: it reads a line.
If you have any other clue to determine 'end-of-input', you can read the input character by character until the 'end-of-input' condition is true. This may be another character or a special sequence of characters like a closing tag if you look at an xml input.