Want to print text char by char for my textbased g

2019-08-13 12:08发布

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条回答
干净又极端
2楼-- · 2019-08-13 12:26

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();
    }
查看更多
该账号已被封号
3楼-- · 2019-08-13 12:30

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.

查看更多
贪生不怕死
4楼-- · 2019-08-13 12:33

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

查看更多
登录 后发表回答