问题
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.
回答1:
From the JavaDocs :
The available method for class InputStream always returns 0.
As System.in is an InputStream , this would explain your problem.
回答2:
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).
回答3:
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.
回答4:
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();
}
}
}
- Create a main loop inside a thread with do your business (Here, I print out: "A loop"
- Start that thread
- Waiting for a key from console
- 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
回答5:
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.
来源:https://stackoverflow.com/questions/36154403/how-to-properly-end-a-while-loop-using-a-key-press