想要为我的基于文本的游戏逐个字符打印文本char,但在总延迟后打印出整个文本 [英] Want to print text char by char for my textbased game, but it prints out the whole text after the summed delay

查看:105
本文介绍了想要为我的基于文本的游戏逐个字符打印文本char,但在总延迟后打印出整个文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图逐个字符逐个打印出一些字符char,问题是它等待然后等待,然后将整个句子打印出来.就像将char逐个字符打印到一个字符串,然后在完成后将该字符串打印出来:

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

请帮助(:

推荐答案

为什么不使用

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

请参见通过睡眠暂停执行

如何正确使用线程睡眠

这篇关于想要为我的基于文本的游戏逐个字符打印文本char,但在总延迟后打印出整个文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆