0

電子部品を制御するプログラムがあります。私の問題は、カウントダウンの部分です。実際には、main メソッドからクラス CountDown を呼び出すと、main には戻りません。プログラムは常にアクティブである必要があり、呼び出しのためにメインの最初の値を読み取り、カウントダウンを開始します。これはコードです:

public class CountDown
{
    public static int a;
    public static Timer timer;

    public CountDown()
    {
        timer = new Timer();
        timer.schedule(new DisplayCountdown(), 0, 1000);
    }

    class DisplayCountdown extends TimerTask
    {
        int seconds = 15;
        public void run()
        {
            if (seconds > 0)
            {
                System.out.println(seconds + " seconds remaining");

                if(READING BY ELECTRONIC COMPONENT == 1)
                {
                    seconds=15;
                } else {
                    seconds--;
                }
            } else {
                System.out.println("Countdown finished");
                CountDown.a=0;
            }
        }
    }

    public static void main(String args[])
    {
        CountDown.a = 0;

        while(true)
                {
         if(READING ELECTRONIC COMPONENT == 1)
         {
            if (CountDown.a==0)
            {
                CountDown.a = 1;
                new CountDown();
            }
        }
    }
}
4

1 に答える 1

0

I've checked to make sure my suspicions are correct. It's not that your new Countdown() isn't returning to the main method, it's that it returns immediately. What you want is likely to do some kind of waiting in the while(true) loop and checking whether or not the countdown is completed. Something along the lines of:

CountDown countDown = null;
while(true)
{
    if (countDown == null || getReading() == 1)
    {
        if (CountDown.a == 0)
        {
            CountDown.a = 1;
            countDown = new CountDown();
        }
    }
    while (countDown.isRunning())
    {
        try
        {
            Thread.sleep(countDown.getRemainingSeconds() * 1000);
        }
        catch (InterruptedException ex)
        {
            // Ignore.
        }
    }
}

Obviously you'll need to implement the isRunning and getRemainingSeconds methods (you could always sleep for a set amount rather than trying to wait exactly the right amount of time if you want).

I'd also recommend trying to make this class better suited for re-use by avoiding the static variables a and timer (use private variables and setters/initialise them in the constructor instead).

于 2012-07-24T11:57:47.467 に答える