Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
479 views
in Technique[技术] by (71.8m points)

java - making text appear delayed

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.

EDIT: 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);
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

[Update]

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...