Skip to main content

APIzation: Replication Package

[Q#25166215][A#25166264] How to add delay to while loop

https://stackoverflow.com/q/25166215

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; So, thanks for reading and appreciate the help in advance.

Answer

https://stackoverflow.com/a/25166264

Change your code to this

APIzation

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);
        }
    }
}
package com.stackoverflow.api;

public class Human25166264 {

  public static void delayedWhileLoop(int delay) throws InterruptedException {
    int countdown = 1;
    while (countdown < 10) {
      System.out.println(countdown);
      ++countdown;
      Thread.sleep(delay);
    }
  }
}

package com.stackoverflow.api;

/**
 * How to add delay to while loop
 *
 * @author APIzator
 * @see <a href="https://stackoverflow.com/a/25166264">https://stackoverflow.com/a/25166264</a>
 */
public class APIzator25166264 {

  public static void addDelay() throws InterruptedException {
    int countdown = 1;
    while (countdown < 10) {
      System.out.println(countdown);
      ++countdown;
      Thread.sleep(1000);
    }
  }
}