Misha
Misha

Reputation: 190

Java: can't get readline() to work

I am trying to parse some input test cases for a competitive programming problem, but the program just sits and waits even though I am reading the entire line and the "\n" character.

Here is the code:

public static void main(String[] args) throws IOException {
    String result = "", input = "";
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    while((input = br.readLine()) != null){
        result += input;   
    }
    System.out.print(result);
}

This is super-simplified, but it still doesn't work. When I enter (without quotes) "1 2 3 4 5 6 7 8 9" and then press enter, it just waits for more input. How can I make it work so that after I press enter, the programs leaves the while loop?

Can I make this work for multiple lines as well? For instance, after the last "\n", if there are no more characters, then break out of the loop.

Thank you for your help. :)

Upvotes: 1

Views: 1395

Answers (2)

smac89
smac89

Reputation: 43078

After you press enter, ctrl + z on windows, ctrl + d on Linux, or cmd + d on Mac.

These keyboard shortcuts are used in their respective Os's to signal EOF to the OS which will in turn notify the jvm.

Another way to do it without using cmd + d is to do java myprogram <<< "1 2 3 4 5 6 7 8 9" Or put the string in a file call myprogram.in then do java myprogram < `cat myprogram.in`

Upvotes: 1

nhouser9
nhouser9

Reputation: 6780

Simply call readLine() once. You have it in a loop. If you call it one time, it should read one line.

Here is the documentation on readLine(): http://docs.oracle.com/javase/7/docs/api/java/io/BufferedReader.html#readLine()

It statues that it will return null only if the end of stream is reached. As you are using System.in as your input stream, you will not reach the end of it just by pressing enter.

Upvotes: 2

Related Questions