使文本出现延迟 [英] making text appear delayed

查看:66
本文介绍了使文本出现延迟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过以下方式显示文本:

I want to make text appear in the following way:

H
wait 0.1 seconds
He
wait 0.1 seconds
Hel
wait 0.1 seconds
Hell
wait 0.1 seconds
Hello

但是我不确定该怎么做.任何帮助将不胜感激.

But I'm not sure how to do it. Any help would be appreciated.

我希望我能够以不需要我做System.out.print();的方式来做到这一点.每个字母.

I'm hoping that I will be able to do it in a way that doesn't require me to make a System.out.print(); for each letter.

这是我的代码.不再有问题,它工作得很好,谢谢.

EDIT 3: Here's my code. EDIT 4: No more problems, it worked perfectly, thanks.

import java.util.Scanner;
import java.util.concurrent.TimeUnit;
public class GameBattle
{
public static void main(String[] args) throws Exception {
    printWithDelays("HELLO", TimeUnit.MILLISECONDS, 100);
}

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

推荐答案

您可以使用 Thread.sleep 或更具可读性的方式(以 0.1s 间隔打印每个字母)至少对我来说)使用 TimeUnit.MILLISECONDS.sleep 例如

You can print each letter in 0.1s interval using Thread.sleep or more readable way (at least for me) using TimeUnit.MILLISECONDS.sleep for example

print first letter;
TimeUnit.MILLISECONDS.sleep(100);
print second letter
TimeUnit.MILLISECONDS.sleep(100);
...

[更新]

我希望我能够以一种不需要我制作System.out.print();的方式来做到这一点.每个字母.

I'm hoping that I will be able to do it in a way that doesn't require me to make a System.out.print(); for each letter.

我认为没有任何理由不这样做.

I don't see any reason not to do it this way.

public static void main(String[] args) throws Exception {
    printWithDelays("HELLO", TimeUnit.MILLISECONDS, 100);
}

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

这篇关于使文本出现延迟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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