想要为我的基于文本的游戏逐个字符地打印文本,但它在总延迟后打印出整个文本

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

我试图延迟打印出一些字符一个字符的文本,问题是它等待啊等待,然后打印出整个句子。这就像一个字符一个字符地打印成一个字符串,然后在完成后打印该字符串:

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

请帮忙(:

您可能会发现调用 flush() 会起作用,但不能保证。

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

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.

你 运行 的价值观是什么?如果您使用的睡眠值太小,因为您将所有内容都打印在一行中,所以它看起来像是一次写入。

尝试 运行 使用这些值来延长睡眠时间。您也可以尝试使用 System.out.println 而不是 System.out.print 来向您展示它实际上是一次打印一个。

    try {
        printWithDelay("Some Text", TimeUnit.SECONDS, 5L);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

你为什么不用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();
    }
}

Pausing Execution with sleep

How to properly use thread sleep