1

Im trying to print out some text char by char with some delay, the problem is that it waits and waits and then prints the whole sentence out. It's like it's printing char by char to a string and then printing that string out once its finished:

public static void printWithDelay(String data, TimeUnit unit, long delay) 
  throws InterruptedException {
    for (char ch : data.toCharArray()) {
        System.out.print(ch);
        unit.sleep(delay);
    }
}

please help (:

3 Answers3

1

Why don't you use Thread.sleep()?

import java.lang.*;

public class PrintWithDelayExample {
    public static void main(String[]args) {
        printWithDelay("Hello! World", 500);
    }

    public static void printWithDelay(String data, long delay) {
        for (char c : data.toCharArray()) {
            try {
                Thread.sleep(delay);
                System.out.print(c);
            } catch (InterruptedException e) {}
        }
        System.out.println();
    }
}

See Pausing Execution with sleep

And How to properly use thread sleep

Community
  • 1
  • 1
Frakcool
  • 10,915
  • 9
  • 50
  • 89
  • It will not allow me to do it in under 300 milliseconds and that is way too slow... Is it really impossible to do it under 300? – Daniel Winkel-Pedersen Oct 08 '15 at 15:49
  • Not for me. For me if it is under 300 millis, it will just wait lets say 100millis pr. char and then when it is done, it will print it all out in one go... /: – Daniel Winkel-Pedersen Oct 08 '15 at 15:56
  • Is it waiting and then printing all in one go? Did you copy-pasted my code and tested it and saw how it's working? With the current code you posted it's almost impossible to provide more help – Frakcool Oct 08 '15 at 16:01
  • Yeah it's copy pasted, but as i said, then it workes perfectly on 300 millis +, but it doesn't work proberly at under 300 millis – Daniel Winkel-Pedersen Oct 08 '15 at 16:03
  • But what happens under 300 millis? `but it doesn't work proberly at under 300 millis` doesn't provide enough information to see what's not working – Frakcool Oct 08 '15 at 16:04
  • It is as if it is working "behind the scenes", by that i mean, it is waiting for as long as it takes to print the whole text out, but instead of printing every char one at a time, it prints the whole text out when it is "done". – Daniel Winkel-Pedersen Oct 08 '15 at 16:06
  • I may have to just quit it /: – Daniel Winkel-Pedersen Oct 08 '15 at 16:22
  • @DanielWinkel-Pedersen I'll try to make a GIF demonstrating how it works, just I'm waiting for an answer from other user who may help me with which tool he used (as I lost it). Then you could try using it to show me how your problem looks like. Or if you know how, then show me :) – Frakcool Oct 08 '15 at 19:18
  • There isn't really much to show... When i debug and come to the line where im using my method with 10 milliseconds, nothing happens.. no output.. it jumps right past it .. – Daniel Winkel-Pedersen Oct 08 '15 at 19:41
  • 10 millis... maybe your computer is "lagging" while executing program. At 10 millis can your eyes see that? It's too low speed to see how each letter is printed. Try writing a larger text – Frakcool Oct 08 '15 at 19:46
  • That is not the problem, im using 100 chared strings, with 10 methodcalls on 10, 20, 30, 40, 50, 100, 150, 200, 250 etc. millis, And no it is not the lagg... Maybe it is NetBeans? – Daniel Winkel-Pedersen Oct 08 '15 at 20:16
  • Probably... try compiling and running on terminal (cmd) :) Might help – Frakcool Oct 08 '15 at 20:48
  • Which Operating System are you using? – Frakcool Oct 08 '15 at 20:49
  • I am using windows 10 – Daniel Winkel-Pedersen Oct 08 '15 at 20:52
  • Open CMD (Windows + R -> write `cmd`) then `cd` to the path where your file is (I recommend desktop and place there the file with the code I posted), then write `javac PrintWithDelayExample.java` (it should compile with no errors) after that `java PrintWithDelayExample` and you should see how it works. – Frakcool Oct 08 '15 at 20:55
  • @DanielWinkel-Pedersen then? did it worked? Or wasn't I clear enough somewhere? – Frakcool Oct 08 '15 at 21:29
  • i do as following: cd C:\Users\danie\Desktop\DungeonGame\src\dungeongame enter java main enter And it says unable to find or locate main class main – Daniel Winkel-Pedersen Oct 08 '15 at 21:30
  • Please create a new file on your desktop, with the code I provided, then `cd` to your desktop and write `javac PrintWithDelayExample.java` after it compiles write `java PrintWithDelayExample`. So you can see how my example works. The error you're getting is because there's no `main` method on `main` class (Maybe your class has a different name) – Frakcool Oct 08 '15 at 21:34
  • Congratulations! I don't like NetBeans but instead I program on notepad++ and compile on cmd as I showed you. Except for debugging. – Frakcool Oct 08 '15 at 21:36
  • Seriously i am really really thankful for your help, as others have given up helping me (: – Daniel Winkel-Pedersen Oct 08 '15 at 21:38
  • Just make sure to help others in the future as I did. And next time provide an [MCVE](http://stackoverflow.com/help/mcve) instead of a code fragment however it was fine. Good luck! – Frakcool Oct 08 '15 at 21:39
  • What do you mean by MCVE? I'm a brand new member at stackoverflow, and will try to help as much as i can (: – Daniel Winkel-Pedersen Oct 08 '15 at 21:43
  • Read the link I provided **M**inimal **C**omplete and **V**erifiable **E**xample is what MCVE stands for. – Frakcool Oct 08 '15 at 21:45
0

You may find calling flush() will work but there is no guarantee.

public static void printWithDelay(String data, TimeUnit unit, long delay)
        throws InterruptedException {
    for (char ch : data.toCharArray()) {
        System.out.print(ch);
        // Add this.
        System.out.flush();
        unit.sleep(delay);
    }
}

See flush()

Flushes this output stream and forces any buffered output bytes to be written out. The general contract of flush is that calling it is an indication that, if any bytes previously written have been buffered by the implementation of the output stream, such bytes should immediately be written to their intended destination.

OldCurmudgeon
  • 64,482
  • 16
  • 119
  • 213
  • @DanielWinkel-Pedersen - Works fine for me. You may have to replace `System.out` with an unbuffered version somehow.That's what the quote means by **is an indication that** - i.e. there is no guarantee it will work. – OldCurmudgeon Oct 08 '15 at 15:05
  • @DanielWinkel-Pedersen - see [here](http://etutorials.org/Programming/Java+performance+tuning/Chapter+8.+IO+Logging+and+Console+Output/8.1+Replacing+System.out/) for why and how. – OldCurmudgeon Oct 08 '15 at 15:08
  • This is waay to technical for my level or programming /: I just really dont understand why it works for you and not me? – Daniel Winkel-Pedersen Oct 08 '15 at 15:13
0

What values are you running this with? If you are using too small of a sleep value, since you are printing everything on one line, it may seem like it is writing all at once.

Try running it with these values to exaggerate the sleep time. You could also try using a System.out.println instead of System.out.print to show you that it is in fact printing one at a time.

    try {
        printWithDelay("Some Text", TimeUnit.SECONDS, 5L);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
nLee
  • 1,320
  • 2
  • 10
  • 21
  • Thanks nLee, it works at 300 Milliseconds, but that is too slow.. And it is on 100 Milliseconds, so it shouldn't be instant.. The problem is that if it is under 300 mili, it waits for the whole text to be done, and the prints it out – Daniel Winkel-Pedersen Oct 08 '15 at 15:19