-1

So I was wondering if there was anyway I could implement this code so that it pauses on each loop iteration. Currently, when I run the code, the program will stop for n seconds (n being the amount of loop iterations) and then display everything at once. However, I wish for it to display one item, wait one second and display the next item. I hope this is clear.

while(x > 0 || y > 0){
        Try{
            Thread.sleep(1000);
        } catch (InterruptedException ie) {
            ie.printStackTrace();
        }

        // Print x and y
        //Change x and y vals

        }
    }
dimo414
  • 42,340
  • 17
  • 131
  • 218
  • Are you asking how to flush stdout? If so, see http://stackoverflow.com/questions/7166328/when-why-to-call-system-out-flush-in-java –  May 28 '15 at 16:52

3 Answers3

0

Suggestion: separate the thread sleep in a method to do the job without rewriting all this code.

Suggestion 2: search aroung if thread sleep is the best solution for you

Try this:

    public void waitSeconds(int seconds){
       try{ 
           Thread.sleep(seconds*1000l); 
       } catch(Exception e) {
          e.printStackTrace(); //ugly but enough to explain
       };
    }
    public void yourMethod(){
        while(x > 0 || y > 0){
            waitSeconds(1);
            print x
            waitSeconds(1);
            print y
            //Change x and y vals    
            }
    }
Solano
  • 520
  • 2
  • 9
  • 1
    You should never suppress `InterruptedException`. – dimo414 May 28 '15 at 16:57
  • 1
    The edit still suppresses the exception, it's just noisier. If the thread is interrupted, you should propagate the interruption, not suppress it. – dimo414 May 28 '15 at 17:01
0

First, don't suppress InterruptedException. If there's nothing to be done about it, simply don't catch it at all, or convert it into a RuntimeException e.g.

throw new RuntimeException(ie);

Second, it sounds like you're describing a flushing problem, which can be addressed by adding calls to:

System.out.flush();

After you print your values. As mentioned in the linked question however, System.out and System.err auto-flush whenever a new line is printed; are you not printing to stdout, or not printing new lines?

You should have a Thread.sleep() call wherever you need the program to pause, so if you need to pause between printing x and y, add another Thread.sleep() between them.

Community
  • 1
  • 1
dimo414
  • 42,340
  • 17
  • 131
  • 218
-1

It's really strange. Try this way:

while(x > 0 || y > 0) {
    // Print old values
    // Change your x and y
    // Print new values

    try {
        TimeUnit.SECONDS.sleep(y);
    } catch(InterruptedException ex) {}
}
Ivan
  • 488
  • 1
  • 5
  • 19
  • You should not suppress `InterruptedException`. Additionally, `TimeUnit.sleep()` calls `Thread.sleep()`, so this is no help. – dimo414 May 29 '15 at 00:44