在java

时间:2018-01-17 11:55:46

标签: java timer

我正在进行一次定时测验,每个问题都应该有一个计时器。

我希望我的代码输出一个问题20秒并要求输入答案,当时间到了,问题编号2应该出现。我被困在应该做什么,参考就足够了,我只是不知道要阅读什么,我正在使用java.util.TimerTimerTask

我也试过

ExecutorService但我只看到它在计时器关闭后的示例,我需要在计时器结束后发布另一个问题,而不是击落程序,因为我需要每个问题的时间限制而不是计时器整个测验。

我试过这个

if(seconds<=20)
{
    question1();
}
else if (seconds<=40||seconds>=21)
{
    new ProcessBuilder("cmd","/c","cls").inheritIO().start().waitFor();
    question2();
}

我也尝试过使用

while(seconds<=20){
    question1();
}
while(seconds<=40||seconds>=21){
    new ProcessBuilder("cmd","/c","cls").inheritIO().start().waitFor();
    question2();
}

这就是我的问题方法。

public static void question2(String... args) throws 
    IOException, InterruptedException
{  
    System.out.println("");
    System.out.printf("%72s\n","QUIZ FOR PHILIPPINE HISTORY");
    System.out.println("");
    System.out.printf("%64s\n","Question #2");
    System.out.println("");
    System.out.println("\t\t\t\t\t     WHO DISCOVERED PHILIPPINES?");
    System.out.println("\n\t\t\t\t\t\tA. Fernando Magellan");
    System.out.println("\t\t\t\t\t\tB. Ferdinand Megallan");
    System.out.println("\t\t\t\t\t\tC. Ferdinand Magellan");
    System.out.println("\t\t\t\t\t\tD. Fernando Poe");

    System.out.println("\n\t\t\t\t\t\tTYPE YOU ANSWER HERE: ");
    char answer2 = a.nextLine().charAt(0);
    switch (sagot2)
    {
        case 'B':
        case 'b':
            score++;
            seconds = 21;
            System.out.print("You are CORRECT!");
            break;
        default:
            System.out.print("You are WRONG");
            seconds = 21;
            break;
    }
}

这是我的代码加上计时器和时间任务的开始。

import java.util.Timer;
import java.util.TimerTask;
import java.util.Scanner;
import java.io.IOException;
public class q2 {
static int seconds = 0; 
static Scanner a=new Scanner(System.in);
static Timer timer = new Timer();
static int number = 1;
static int score = 0;
public static void mema(){
    TimerTask task = new TimerTask () 
    {
        public void run() 
        {
            seconds++;
            System.out.print(seconds);
        }
    };

    timer.schedule(task,1000,1000);
}   

我也尝试过使用它,但是在5秒钟后它没有用另一种方法。

long start = System.currentTimeMillis();
long wait = 5000;
long end = start + wait;
long end1 = end + wait;

while (System.currentTimeMillis() < end)
{
question1();
}
while (System.currentTimeMillis() < end1 || System.currentTimeMillis() > end)
{
question2();
}

1 个答案:

答案 0 :(得分:1)

你所做的各种事情使你的代码变得更加复杂。

首先,避免修复等详细信息,例如&#34;这是第一个问题&#34;与#34;这是第二个问题&#34;。

相反:专注于您需要的基本元素。在您的情况下:您想要在一定时间内显示问题。之后,程序应该显示另一个问题 - 或者可能给出摘要并结束。

因此:写一个简单提出问题然后等待的类/方法。然后考虑如何重新使用该代码按顺序提出任意数量的问题。

对于&#34;时间&#34;:鉴于你是初学者,我建议你不要去完全多线程&#34; (此处为:任务和调度程序)。相反,&#34;等待一段时间&#34;可以通过

轻松实现
  • 获取currentTime
  • endTime = currentTime + 20秒
  • 循环直到达到endTime

事情是:你通过探索你的选择并尝试很多东西来学习编程。因此我给了你提示 - 而不是代码。