java - 尝试对计时器进行编程,以便用户只能在一定时间内输入单词

标签 java timer

我正在尝试制作一款只能输入 10 秒单词的游戏。我尝试创建一个多线程解决方案,但它无法正常工作。

class timer extends Thread{//thread
public void run(){
    for(int i=10;i>=0;i--){
        System.out.print(i+" ");
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
}

主要方法:

            timer t=new timer();
            t.start();
            while () {//not sure what to put in my while statement
                System.out.print("Guess a word on the board! ");
                if(test.CheckGame(scan.next())==true){
                    System.out.print("Good job! ");
                }
                else    
                    System.out.print("Guess again! ");
            }

本质上,在线程运行 10 秒并终止后,我希望它返回一个 Break 语句,以便程序离开 while 循环。有什么建议么?

最佳答案

将您的代码更改为此

timer t=new timer();
t.start();
while (t.isAlive()) {//not sure what to put in my while statement
    System.out.print("Guess a word on the board! ");
    if(test.CheckGame(scan.next())==true){
        System.out.print("Good job! ");
    }
    else    
        System.out.print("Guess again! ");
}

一旦 run 函数退出,t.isAlive 将为 false。您可能还需要传递计时器对象并检查该对象的 isAlive(),具体取决于 CheckGame 的工作方式。这样,输入就无法在 10 秒后无限期地输入。

关于java - 尝试对计时器进行编程,以便用户只能在一定时间内输入单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15732362/

相关文章:

android - 如何在 LIBGDX 中设置定时器

c# - 告诉任务等到计时器停止

java - 给定日期和时间值,我如何在时间表中找到下一个类?

java - 为什么 12 Factor 应用程序应该是独立的?

java - 在 pom.xml 中包含 proguard 配置文件

javascript - 嵌套类的范围问题

swift - 定时器的替代品

linux - 我正在尝试在 ubuntu 中使用 c 实现计时器,但收到声明错误

java - 如何验证 UTF-8 字符串是否包含错误编码的字符

java - 无法使用 Play Framework 2.4.x 和 IntellijIdea 14.x 解决符号 'play' 错误