简体   繁体   English

如何在 java 的 for 循环中进行延迟?

[英]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).我正在尝试在 Java (BlueJ) 中的 for 循环中添加暂停。 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"当我使用Thread.sleep(1000)时,我最终得到一个异常:“必须捕获或声明抛出未报告的异常 java.lang.InterruptedException”

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:您需要将 Thread.sleep(1000) 代码放入循环中,如下所示:

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.而且我建议你用InterruptedException异常处理封装Thread.sleep(1000)。

Here are some examples of how you can do it.以下是一些如何做到这一点的示例。 Java Delay/Wait Java 延迟/等待

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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