Want to print text char by char for my textbased game, but it prints out the whole text after the summed delay

混江龙づ霸主 提交于 2019-12-24 11:35:52

问题


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


来源:https://stackoverflow.com/questions/33019295/want-to-print-text-char-by-char-for-my-textbased-game-but-it-prints-out-the-who

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!