如何在if语句中使用计时器

时间:2019-03-29 00:30:20

标签: java timer int

我需要每x时间更新游戏中的食物数量。我想使用if语句,但是它不能工作,因为我猜计时器和int不能一起工作?

Timer timer = new Timer(200, this);
    public void update()
    {
        double dt = 0;
        timer += dt;
        if(timer > 1000)
        {
            food++;
            timer = 0;
        }
    }

1 个答案:

答案 0 :(得分:0)

我建议在此使用实时。您只需要有2个变量(上次提要的时间和现在的时间)即可。只需计算时差并将其置于您的if条件中即可。请参考以下示例:

import java.util.Date;

public class Main {
    public static Date lastDate = new Date();
    public static int food = 0;

    public static void main(String args[]) {
        System.out.println("Food was added on " + lastDate.toString() + ". Food now is " + food);
        while (food < 5) {
            update();
        }
    }

    public static void update() {
        Date dateNow = new Date();
        // in milliseconds
        long diff = dateNow.getTime() - lastDate.getTime();

        long diffSeconds = diff / 1000 % 60;
        // long diffMinutes = diff / (60 * 1000) % 60;
        // long diffHours = diff / (60 * 60 * 1000) % 24;
        // long diffDays = diff / (24 * 60 * 60 * 1000);

        // If more than 5 seconds have passed
        if (diffSeconds > 5) { // just change this to your desired interval
            lastDate = new Date(); // get the time now
            food++; // increment food
            System.out.println("Food was added on " + lastDate.toString() + ". Food now is " + food);
        }
    }
}

输出:

Food was added on Fri Mar 29 09:15:08 SGT 2019. Food now is 0
Food was added on Fri Mar 29 09:15:14 SGT 2019. Food now is 1
Food was added on Fri Mar 29 09:15:20 SGT 2019. Food now is 2
Food was added on Fri Mar 29 09:15:26 SGT 2019. Food now is 3
Food was added on Fri Mar 29 09:15:32 SGT 2019. Food now is 4
Food was added on Fri Mar 29 09:15:38 SGT 2019. Food now is 5