如何使用按键正确结束while循环? [英] How to properly end a while loop using a key press?

查看:530
本文介绍了如何使用按键正确结束while循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个while循环,该循环将一直运行到按键. 我正在使用此代码:

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.

推荐答案

好,对于控制台应用程序,您是否尝试过System.in.read()?这是一个示例的链接: http://www.java2s.com/代码/JavaAPI/java.lang/Systeminread.htm

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

我将在下面保留我的答案,以供后代以及正在寻找与具有UI的应用程序类似的答案的其他人. 您将要使用KeyListener捕获按键事件.这是一个如何实现它的例子. http://docs.oracle.com/javase/tutorial/uiswing/events /keylistener.html

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

然后,您可以循环播放并查看在发生按键时设置的标志.您可能希望在循环过程中睡一小段时间(250或500ms),否则您将创建一个循环,以非常快的速度吸收所有计算周期.

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.

这篇关于如何使用按键正确结束while循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆