问题描述
我正在尝试制作一个游戏,您只能输入 10 秒钟的单词.我试图创建一个多线程解决方案,但它不能正常工作.
I am trying to make a game where you can only enter words for 10 seconds. I tried to create a multithread solution but it doesn't work properly.
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 循环.有什么建议?
essentially, after the thread goes for 10 seconds and terminates,I want it to return a break statement so the program leaves the while loop. Any suggestions?
推荐答案
这是一个简单的 Demo,可以让您了解如何使用 java.util.Timer
.
Here is a simple Demo that would let you to know how to use java.util.Timer
.
import java.util.Timer;
import java.util.TimerTask;
import java.util.Scanner;
class Tester
{
static long i = 0;
public static void main(String[] args) throws Exception
{
Scanner scanner = new Scanner(System.in);
System.out.println("You have only 10 seconds to find the result");
System.out.println("What is the value of : 111111 X 111111 ");
Timer timer = new Timer("Timer");
timer.schedule(new TimerTask()
{
public void run()
{
if (i == 12345654321L)
{
System.out.println("Congrats!! you guessed the write answer :)");
}
else
{
System.out.println("Sorry Time is over. You couldn't guess the correct answer.");
}
System.exit(0);
}
},10 * 1000 , 1);
while (true)
{
i = scanner.nextLong();
if ( i == 12345654321L)
{
System.out.println("Congrats!! you guessed the write answer :)");
System.exit(0);
}
else
{
System.out.println("Try next guess :");
}
}
}
}
编辑
因为我没有你的所有代码,所以我在这里发布了你根据我的基本假设回答的解决方案.不要使用线程.而是使用 java.util.Timer
.您的代码如下所示:
Since I don't have your all code so I am posting here the solution for your answer on my basic assumption. Don't use Thread. Instead use java.util.Timer
. Your code would look as follows:
static String input=" ";//created a static variable input to take input
public static void main(String st[])
{
Timer timer = new Timer("Timer");
timer.schedule(new TimerTask()
{
public void run()
{
if (test.CheckGame(input))
{
System.out.println("Congrats!! you guessed the write answer :)");
}
else
{
System.out.println("Sorry Time is over. You couldn't guess the correct answer.");
}
System.exit(0);
}
},10 * 1000 , 1);//waits for 10 seconds
while (true)
{
System.out.print("Guess a word on the board! ");
input = scan.next();
if(test.CheckGame(input))
{
System.out.print("Good job! ");
System.exit(0);
}
else
{
System.out.println("Bad Guess. Try again ");
}
}
}
这篇关于尝试对计时器进行编程,以便用户只能在一定时间内输入单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论