我使用Java制作了一个计时器,在十五秒后显示“Time is up”消息。在此期间,用户将输入要复制的消息。但在那段时间结束后,我希望键盘输入停止。这是代码:
主要课程
import java.util.Scanner;
public class TypingTest
{
public static void main(String[] args)
{
boolean a;
String message, enter;
Watch watch = new Watch();
Scanner input = new Scanner(System.in);
System.out.println("After you press <enter>, you will have fifteen seconds to copy the message.");
System.out.println("Once you are finished, do not press any other button until prompted to.");
enter = input.nextLine();
a = watch.timer(15,"Time's up! Press <enter> to see how you did."); // message appears after 15 seconds
if (a == true)
message = input.nextLine(); // While timer is running
else
message = null; // After timer is done running
}
}
Watch类中的Timer方法
import java.util.Timer;
import java.util.TimerTask;
class Watch
{
private boolean running;
public Watch()
{
running = false;
}
public static boolean timer(long delay, final String message)
{
running = true;
delay *= 1000; // Convert from milliseconds to seconds
final Timer timer = new Timer();
timer.schedule(new TimerTask()
{
public void run()
{
System.out.println(message); // message output after 'delay' seconds
timer.cancel();
running = false;
}
}
,delay); // delay in seconds
return running;
}
}
任何建议都将不胜感激。
答案 0 :(得分:0)