1

i am trying to create a while loop that will run until keypress. I am using this code:

while (System.in.available() == 0){
            // do something
    }

unfortunately, this is not working. is there any way around it? what could be the reason for this? i should mention that during the loop i am printing things to the console, could this be the reason?

any help would be appreciated, thank you for your help.

  • `Ctrl+C` works for most terminals. – Kody Mar 22 '16 at 12:36
  • I am not trying to terminate the entire program, just to end this specific loop. –  Mar 22 '16 at 12:38
  • Have you considered the KeyListener class? – Chris Gong Mar 22 '16 at 12:43
  • why do you want to close it on keypress,instead use condition in your while loop to terminate it –  Mar 22 '16 at 12:44
  • @StoyanDekov what do you mean? during the loop i am trying to hit the `Enter` key and nothing happening. it does not have to be a key press, maybe it is possible to enter string like 'exit' or something. –  Mar 22 '16 at 12:45
  • @DaneBrick i have but i dont quite understand how to implement that yet. –  Mar 22 '16 at 12:46
  • @PrayagSharma i got my reasons :-). basically the condition is the key pressing. –  Mar 22 '16 at 12:47
  • what kind of app you are using ? Forms or console ? – Basil Battikhi Mar 22 '16 at 13:24
  • No forms. Just runnig it regularly in the eclips. Console i guess. –  Mar 22 '16 at 13:28

5 Answers5

0

From the JavaDocs :

The available method for class InputStream always returns 0.

As System.in is an InputStream , this would explain your problem.

jr593
  • 287
  • 1
  • 8
  • 1
    This is not what he wants. – dryairship Mar 22 '16 at 12:38
  • Sorry, forgot to mention. Waiting for Keypresses depends on jre implementation. – jr593 Mar 22 '16 at 12:39
  • @user3181718 what do you mean? all i want is that on any key press that specific loop will break. there is more code after the loop which i want to execute after that loop stopped. –  Mar 22 '16 at 12:41
0

If you want to have the loop running constantly, and stop as soon as you press any key, you'll have to use additional libraries for that (at least jline and jcurses exist). Using the standard methods, you'll have to press enter to flush the buffers, and it won't work smoothly like you probably want it to.

Also, you never ever need to use available() (and it won't do what you hope).

Kayaman
  • 72,141
  • 5
  • 83
  • 121
0

Ok, for console applications, have you tried System.in.read()? Here's a link to an example: http://www.java2s.com/Code/JavaAPI/java.lang/Systeminread.htm

I'll leave my answer below for posterity and other people who are looking for a similar answer to applications with a UI. You'll want to use a KeyListener to capture the key pressed event. Here's an example of how to implement it. http://docs.oracle.com/javase/tutorial/uiswing/events/keylistener.html

Then, you can loop and look at a flag that you set when a keypress occurs. You may want to sleep for short bits (250 or 500ms) during the loop or you'll be creating a loop that will absorb all of the compute cycles very fast.

wandercoder
  • 392
  • 2
  • 16
  • Ah, I missed the clue about the console. – wandercoder Mar 22 '16 at 12:59
  • I added to the beginning how to handle console apps. – wandercoder Mar 22 '16 at 20:15
  • @wandercoder i am trying to implement the KeyListener method. i have added `Implements KeyListener` to my class declaration. i have added the `KeyPressed` , `KeyReleased` and `KeyTyped` methods. however it wont let me to add the `addKeyListener()`. i am getting an error on this line. i am trying to write: `this.addKeyListener(this);`. what am i doing wrong? –  Mar 23 '16 at 07:39
  • 1
    @Dany Lavrov First of all, if you're still trying to use a console application without a UI, you should try to use the System.in.read() call. But, since you're now looking at the key listener, I gather that you're now trying to use a swing UI. I recommend that you look over and carefully study the KeyListener example that I referenced. You should be listening to key input from a UI element, like a text area, that sends out key events. I suspect that this is your problem. If you want more help, can you post all of your source? – wandercoder Mar 23 '16 at 13:03
-1
public class Test {

    public static void main(String[] args) throws InterruptedException {
        Thread a = new Thread() {
            @Override
            public void run() {
                try {
                    while (true) {
                        System.out.println("A loop");
                        sleep(2000);
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };

        try {
            a.start();
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            br.readLine();
            a.stop();
            a.join();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
  1. Create a main loop inside a thread with do your business (Here, I print out: "A loop"
  2. Start that thread
  3. Waiting for a key from console
  4. Terminate the thread As what I see, you didn't require for a single hit from keyboard to terminate the loop, so, hit a key and then enter
VinhNT
  • 1,091
  • 8
  • 13
-1

Another method is to enable Swing by import javax.swing.*; and use a function for displaying: variable = JOptionPane.showInputDialog(). This activates a window with "Ok" and "Cancel" buttons. This worked properly in my programs.