我如何每秒向一个整数添加一个数字 [英] how do i add a number to an integer every second

查看:179
本文介绍了我如何每秒向一个整数添加一个数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个cookie点击器类型的游戏,我想要一个事物,每秒钟一定数量让我们说5被添加到另一个数字。所以整数变量每秒都会增加5.如何创建一种时间测量方法,它测量时间,以便我可以将数字添加到另一个数字。

I'm making a cookie clicker sort of game and I want a thing where every second a certain number let's say 5 is added to another number. So every second the integer variable is going up by 5. How would I create a sort of time measuring method where it measures time so I can add a number to another number.

public class timeTesting {
    // I've put this method here for someone to create
    // a timer thing
    void timer()
    {

    }
    public static void main(String[] args) {        
        // Original number
        int number = 1;
        // Number I want added on to the original number every 5 seconds
        int addedNumber = 5;
    }
}


推荐答案

你可以使用计时器来安排 TimerTask 谁在run()方法中拥有所需的代码。检查下面的代码(运行()将在5000毫秒后调用一次):

You can use Timer to schedule a TimerTask who has the desired code inside the run() method. Check the code below (run() will be called once after 5000 milliseconds) :

Timer t = new Timer();
    t.schedule(new TimerTask() {
        @Override
        public void run() {
            number += addedNumber;
        }
    }, 5000);

此外,您还可以使用scheduleAtFixedRate(TimerTask任务,长延迟,长周期)来执行重复性任务(此处运行将被立即调用,每5000毫秒):

Also you can use scheduleAtFixedRate(TimerTask task, long delay, long period) for repetitive tasks (here run will be called immediately, and every 5000 milliseconds):

Timer t = new Timer();
    t.scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {
            number += addedNumber;
        }
    }, 0, 5000);

这篇关于我如何每秒向一个整数添加一个数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆