10

I'd like to break out of a loop when the user presses a key.

In C I'd use kbhit(). Is there a Clojure (or Java) equivalent?

justinhj
  • 11,147
  • 11
  • 58
  • 104
  • 1
    What kind of application do you use? Console, Swing, servlets? – ffriend Dec 18 '10 at 21:11
  • Just from a console REPL using swank or otherwise. – justinhj Dec 19 '10 at 03:09
  • 1
    Start new thread (`agent`, `future`, `Thread` or whatever you use), which will do actual processing, save thread variable, from `main` read the input, and when it's not empty, stop your dedicated thread. If you just playing in REPL, [this](http://www.objectcommando.com/blog/2010/06/10/clojure-futures/) will completely cover your needs. – ffriend Dec 19 '10 at 04:02
  • Actually that's what I did for now, but I guess the best solution is to use the Swing library to wait for a key and wrap that in my own kbhit() function – justinhj Dec 19 '10 at 21:27
  • Seems like to use the Swing library I need to make a frame. I wonder if it's possible to make an invisible frame that's only purpose to is to act as a key event listener – justinhj Dec 25 '10 at 21:31

1 Answers1

2

You're looking for nonblocking handling of a key press in a (Linux?) console in Java. An earlier question suggested two Java libraries that might enable this. If it doesn't need to be portable, there is a solution here.

Basically,

public class Foo {
  public static void main(String[] args) throws Exception {
    while(System.in.available() == 0) {
       System.out.println("foo");
       Thread.sleep(1000);
    }
  }
}

works, but (on Linux) only after pressing 'return', because the console inputstream is buffered and that is decided by the OS. This means that you can't overcome that by using Channels or any other NIO class. To make sure the console flushes each and every character, you need to modify the terminal settings. I once wrote a C program that does that (modify the ICANON flag of the termios struct of the current terminal), but I don't know how to do that from Java (but see the second link).

In general, you can find some more in this issue by searching for 'java nonblocking input'.

Community
  • 1
  • 1
Confusion
  • 16,256
  • 8
  • 46
  • 71