theorist17
theorist17

Reputation: 55

BufferedReader readLine() not working in a while loop

When I call readLine() inside the while loop block, somehow, even when I pressed enter, the input won't finish. Looks like, it creates a new line but still waiting for the line input to be terminated.

public static void main(String[] args) throws IOException {
  // TODO Auto-generated method stub
  InputStreamReader isr = new InputStreamReader(System.in);
  BufferedReader br = new BufferedReader(isr);

  String line = "";
  while(!line.equals("End")){
    line = br.readLine();
    System.out.println("String from keyboard not working : "+line+"\n");
  }
  
  while((line = br.readLine())!=null) {
    System.out.println("String from keyboard in while loop : "+line+"\n");
  }
}

When I put readline() on top of while's condition section, it works fine. I want to know why the former while doesn't work.

Upvotes: 0

Views: 2466

Answers (3)

Scary Wombat
Scary Wombat

Reputation: 44854

Not quite sure what trouble you think you are having

But if I run your code at input

test
String from keyboard not working : test

End
String from keyboard not working : End

kkk
String from keyboard in while loop : kkk

Then if I input ctrl-d then the second loop will terminate

even when I pressed enter, enter does not terminate the input, try ctrl-d

Upvotes: 2

Missaka Iddamalgoda
Missaka Iddamalgoda

Reputation: 1059

while(!line.equals("End")){
    line = br.readLine();
    System.out.println("String from keyboard not working : "+line+"\n");
}

This block works fine. In this once you enter End it will Print End once and terminate. The reason for printing is that the condition is checked in the next cycle of the loop.

while((line = br.readLine())!=null) {
    System.out.println("String from keyboard in while loop : "+line+"\n")
}

This block doesn't terminate because every time you hit Enter the terminal sends a Empty String. So if you want it to terminate when you press Enter change the condition to

while(!(line = br.readLine()).equals(""))

Upvotes: 1

Leandro Keen Zapa
Leandro Keen Zapa

Reputation: 196

You called the line variable first before putting any data from the bufferedReader. the first while loop compares "END" with "", so, obviously wrong.

Upvotes: 0

Related Questions