Want to print text char by char for my textbased g

2019-08-13 12:24发布

问题:

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 (:

回答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



回答2:

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.



回答3:

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();
    }