decrease an integer every minute in java

时间:2016-08-31 17:21:27

标签: java timer

I'm trying to make a little game, but I need some help with the code. I want to make a timer that decreases a number every minute, until it is 0.

// i want this to decrease by one every minute
int Food  = 10;

2 个答案:

答案 0 :(得分:0)

You basically need a scheduler which runs every minute. To implement a scheduler, you can create a class which extends java.util.TimerTask.

https://docs.oracle.com/javase/7/docs/api/java/util/TimerTask.html

class YourJob extends TimerTask{

public void run(){
//code which you want to execute every minute
}

}

Now, you need to initialize and register this timer. You can do this using schedule() method of java.util.Timer class

https://docs.oracle.com/javase/7/docs/api/java/util/Timer.html

class Application {

  public static void main(String[] args) {
    Timer timer  new Timer();
    Calendar date = Calendar.getInstance();
    date.set(
      Calendar.DAY_OF_WEEK,
      Calendar.SUNDAY
    );
    date.set(Calendar.HOUR, 0);
    date.set(Calendar.MINUTE, 0);
    date.set(Calendar.SECOND, 0);
    date.set(Calendar.MILLISECOND, 0);
    // Schedule to run every Sunday in midnight
    timer.schedule(
      new YourJob(), //your job class,
      1000*60 //delay in milliseconds
    );
  }
}

答案 1 :(得分:0)

Try this. I have edited code available on this site. It simply makes thread sleep for 60000 miliseconds and then decrement value of the counter (In you case Food). For more information about threads, refer this site. For the sleep method, refer this.

class TestSleepMethod1 extends Thread
{  
    public void run()
    {  
        int Food  = 10; //Initial value
        for(int i=Food;i>0;i--)//Decrementing till it becomes 0
        {  
            try
            {
                Thread.sleep(60000); //Time is in miliseconds here so for your code its 60000
            }
            catch(InterruptedException e)
            {
                System.out.println(e);
            }  
            System.out.println(i);  //Printing value of i in each execution of the loop
        }  
    }  

    public static void main(String args[])
    {  
        TestSleepMethod1 t1=new TestSleepMethod1();       
        t1.start();    
    }  
}