-2

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
Jernej K
  • 1,602
  • 2
  • 25
  • 38
  • 6
    Why are a code block directly in your class? If there isn't, write it with the function. I recommend you to catch the exception. If you don't know about them, read [here](https://www.tutorialspoint.com/java/java_exceptions.htm) – CoderCharmander Oct 18 '19 at 19:21
  • There is no way this compiles.. – RobOhRob Oct 18 '19 at 19:28
  • 1
    Your code is executed in a thread. If you pause it with `sleep` someeone else might interrupt it in the meantime - thats why this method throws an exception. Wrap your call to `Thread.sleep` in a `try-catch`-block. – Glains Oct 18 '19 at 19:37
  • 2
    Who even upvoted this? The upvote button says "This question shows research effort, it is useful and clear." – FailingCoder Oct 18 '19 at 19:42

1 Answers1

0

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

Juliano Pacheco
  • 521
  • 1
  • 5
  • 13