0

I need to be able to interrupt a while loop only when a user enters something. Otherwise the loop should continue.

I tried using if (scanner.nextLine()) however this will cause the loop to wait until something is entered before moving on.

How can I keep the loop continuing until something is entered?

while (true) {
    if (scanner.nextLine()) {
    // statements
    }

    // standard loop statements
}
roeygol
  • 4,908
  • 9
  • 51
  • 88
Adam Jarvis
  • 183
  • 1
  • 13
  • 9
    hm, how would one `break` out of a loop... – janos Nov 28 '16 at 20:12
  • Probably just change `while(true)` to `while(!scanner.hasNext())`. – RaminS Nov 28 '16 at 20:15
  • 1
    _hasNext()_ is blocking. In general, blocking IO is not what you want. How about checking the existence of a file instead? – Kedar Mhaswade Nov 28 '16 at 20:16
  • 1
    Generally reading from console should stop thread which is responsible for it, but if you want to do other things independently execute them in other thread. You can place loop there and execute until it until thread is asked to be interrupted. Anyway proper solution would require proper problem description so that is all I can say for now. – Pshemo Nov 28 '16 at 20:18
  • 1
    I could send you here but that probably creates more questionmarks than you would need. http://stackoverflow.com/questions/18037576/how-do-i-check-if-the-user-is-pressing-a-key – Tacolibre Nov 28 '16 at 20:24

1 Answers1

1

If you want to exit the loop when the user types a single character you might need to listen to a KeyEvent. But if you can wait until the user enters a line of zero or more characters and hits the ENTER key, then you could use the ready method of a BufferedReader.

 InputStreamReader inputStream = new InputStreamReader(System.in);
 BufferedReader bufferedReader = new BufferedReader(inputStream);
 while(true)
 {
     if (bufferedReader.ready())
     {
         String s = bufferedReader.readLine();
         // do stuff before exiting loop
         break;
     }
     // do stuff in loop 
 }
Penguino
  • 2,136
  • 1
  • 14
  • 21