Search code examples
javaarraysfor-loopdelaybluej

How do I make a delay in a for loop in java?


I'm trying to add pauses to a for loop in Java (BlueJ). When I use Thread.sleep(1000), I end up with an exception: "unreported exception java.lang.InterruptedException must be caught or declared to be thrown"

What could be wrong with the code resulting in the exception:

public class R {

  private boolean a;
  private boolean b;

  if(a && b) {
     String[]Array = {"x","y","z"};
     for(int i = 0; i < Array.length; i++, Thread.sleep(1000))
     {
       System.out.print(Array[i]);
     }
  }
}

I want the end result to be the following:

x

//delay

y

//delay

z

Solution

  • You need to put the Thread.sleep(1000) code inside your loop for, like this:

    for(int i = 0; i < Array.length; i++){
       System.out.print(Array[i]);
       Thread.sleep(1000); // if you prefer, you could put before the System.out...
    }
    

    And I recommend that you encapsulate Thread.sleep(1000) with InterruptedException exception handling.

    Here are some examples of how you can do it. Java Delay/Wait