有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何每秒向整数添加一个数字

我正在做一个类似饼干点击器的游戏,我想要一个每秒钟都有一个特定数字的东西,比如说5被加到另一个数字上。所以每秒钟整数变量就增加5。我如何创建一种时间测量方法,它测量时间,这样我就可以把一个数字加到另一个数字上

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;
    }
}

共 (5) 个答案

  1. # 1 楼答案

    如果你的目标是android平台,你可以使用CountDownTimer,它允许你在一定的时间内每隔一定的时间执行一些代码。但是请注意,android并不像J2SE那样使用主方法

    不管怎么说,如果你想开发一款android游戏,我强烈建议你从这里开始:Android Development

  2. # 2 楼答案

    你应该考虑使用一个^{},当某个时间间隔通过时,它将触发一个事件。它也可以每隔一段时间重复一次

  3. # 3 楼答案

    您可以使用Timer来安排一个TimerTask在run()方法中拥有所需代码的人。检查下面的代码(5000毫秒后将调用run()):

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

    您还可以使用scheduleAtFixedRate(TimerTask task,long delay,long period)执行重复性任务(此处将立即调用run,并且每5000毫秒调用一次):

    Timer t = new Timer();
        t.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                number += addedNumber;
            }
        }, 0, 5000);
    
  4. # 5 楼答案

    不是很优雅,但工作代码:

    public class MyTimer {
    
        private volatile int number;  //must be volatile as we're working on multiple threads.
        private final int numberToAdd;
        private final long timerTimeInMillis;
    
        public MyTimer() {
            number = 1;
            numberToAdd = 5;
            timerTimeInMillis = 5000;
        }
    
        public void runTimer() {
            new Thread() {                     //declaring a new anonymous Thread class
                public void run() {            //that has to override run method.
                    while (true)               //run the program in an infinite loop
                    {
                        number += numberToAdd; //add a number
    
                        System.out.println("Added number. Now the number is: " + number);
                        try {
                            Thread.sleep(timerTimeInMillis);  //and then sleep for a given time.
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }.start();                         //and here we're starting this declared thread
        }
    
        public static void main(String[] args) 
        {
            new MyTimer().runTimer();
            try {
                Thread.sleep(100000);          //this application will work for 100sec.
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    

    使用java。util。计时器会更优雅,但在这里,你可能会被匿名类所吸引