0

I am new to Java and today I was trying to read some data from the console using a BufferedReader object. I am reading input inside a while loop and terminating the loop as soon as the user (me) types the exit key, say 'q'. The problem is that, I am not able to type in characters when the program is run, thus my program ends up in an infinite loop. I think my code has no bugs, but still posting it here, may be I am wrong.

public static void main(String args[]) throws IOException
   {
       char c;
       BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

       do
       {
           c = (char) br.read();
           System.out.println(c);
       } while(c != 'q');
   }

So, is there something that my IDE does not support (like console input) or my code is buggy or something else is causing the infinite loop?

  • "The problem is that, I am not able to type in characters when the program is run", you mean you are not seeing console to enter the input or your program prompting repeatedly so you can't enter the input? – kosa Jun 24 '16 at 16:29
  • I can see the console, if the console is where the output is displayed in NetBeans IDE. I can see the cursor blinking but can't type characters. –  Jun 24 '16 at 16:32
  • In Java, a Scanner is the preferred way to get input from the user. See http://stackoverflow.com/questions/5287538/how-can-i-get-the-user-input-in-java – Michael Markidis Jun 24 '16 at 16:35
  • i think you need Scanner not BufferedReader – CSK Jun 24 '16 at 16:36
  • It works fine for me! But if it isn't giving you errors, you probably have things installed correctly... weird – Mr. DROP TABLE Jun 24 '16 at 16:36
  • Yes probably you guys are right, Scanner could be the preferred way. But I just don't want to leave any feature of the core language, unpracticed :-) . –  Jun 24 '16 at 16:38
  • @Devashish Not sure why it is infinite looping; however, even if you were to fix the infinite loop, you would still have "unexpected" results because hitting enter after you type a char will cause the loop to go an extra time since the enter will be read as a char(s). – Michael Markidis Jun 24 '16 at 16:42

0 Answers0