tags:

views:

292

answers:

3

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?

+2  A: 

What exactly do you do and what do you expect? I have two guesses:

  1. You're having a superfluous readLine() at the end of the program. Remove it or change loop conditions appropriately to solve this.
  2. 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 neither BufferedReader nor readLine() are very suitable.
Joey
just checked the loop conditions, no superfluous readLine()...
Pranav
This works perfectly though - public class Buttons{public static void main (String[] args) throws java.lang.Exception{java.io.BufferedReader r = new java.io.BufferedReader (new java.io.InputStreamReader (System.in));String s;while (!(s=r.readLine()).startsWith("42")) System.out.println(s);}}
Pranav
Could you put the code you have into your question with proper formatting? Would be much easier to read.
Joey
This code has the same effect...my mistake.
Pranav
A: 

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.

Andrzej Doyle
+1  A: 

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.

Andreas_D