简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM