-2

I have a while loop and what I want it to do is every 1 second count up an integer up to 10. The code that I have now simply spits out 1-10 as quick as it possibly can with no delay, I'm un-sure how to add a delay. package apackage;

public class loops {
    public static void main(String args[]){
        int countdown = 1;
        while (countdown < 10) {
            System.out.println(countdown);
            ++countdown;
        }
    }
} 

So, thanks for reading and appreciate the help in advance.

user3910313
  • 87
  • 1
  • 2
  • 9
  • 1
    Look at [`Thread#sleep`](http://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html#sleep(long)) – August Aug 06 '14 at 17:11

3 Answers3

4

Change your code to this

public class loops {
    public static void main(String args[]) throws InterruptedException {
        int countdown = 1;
        while (countdown < 10){
            System.out.println(countdown);
            ++countdown;
            Thread.sleep(1000);
        }
    }
} 
odlund
  • 247
  • 1
  • 5
  • 5
    Soon enough someone here will tell you that it's not accurate enough due to the additional time spent on the countdown itself at every iteration. – barak manos Aug 06 '14 at 17:14
1

You may consider Thread.sleep()

Here is the tutorial

JerryDeveloper
  • 139
  • 1
  • 9
1

Add this at the beginning of the loop:

long time = System.currentTimeMillis();

And add this at the end of the loop:

long wait = time + 1000 - System.currentTimeMillis();
if (wait > 0)
    Thread.sleep(wait);
barak manos
  • 29,648
  • 10
  • 62
  • 114