Nick Nicholas
Nick Nicholas

Reputation: 101

Java Timer Code

so I have this code which counts up to 21, but I wanna make a 3 second timer for each number like this:
1
3 seconds later
2
3 seconds later
3
3 seconds later
4

Like that, here is my code, if you got any ideas, can you please help me and do something with it?

package me.Capz.While;

public class WhileLoop {

    public static void main(String args[]) {

        double money = 0;

        while (money < 22) {

            System.out.println(money);

            money++;

        }
    }
}

Upvotes: 0

Views: 105

Answers (4)

JonK
JonK

Reputation: 2108

Probably the easiest way to accomplish this is to use Thread#sleep(long):

package me.Capz.While;

public class WhileLoop {

    public static void main(String args[]) {

        double money = 0;

        while (money < 22) {
            System.out.println(money);
            money++;
            try {
                Thread.sleep(3000L); // The number of milliseconds to sleep for
            } catch (InterruptedException e) {
                // Some exception handling code here.
            }
        }
    }
}

Upvotes: 2

Andr&#233; R.
Andr&#233; R.

Reputation: 1647

Here is an asynchronous, nonblocking solution of your problem statement :

public static void main(String[] args) {
    printAndSchedule(1);
}

public static void printAndSchedule(final int money) {
    if (money < 22) {
        System.out.println(money);
        new Timer().schedule(new TimerTask() {
            public void run() {
                printAndSchedule(money + 1);
            }
        }, TimeUnit.SECONDS.toMillis(3));
    }
}

Upvotes: 1

Crazyjavahacking
Crazyjavahacking

Reputation: 9677

public static void main(String args[]) throws InterruptedException {
    double money = 0;
    while (money < 22) {
        System.out.println(money);
        money++;
        Thread.sleep(3000);
    }
}

Upvotes: 0

Pratik
Pratik

Reputation: 954

User below code.This will pause for a 3 seconds.

System.out.println(money);
Thread.sleep(3000);

Upvotes: 0

Related Questions