making text appear delayed

前端 未结 4 1939
故里飘歌
故里飘歌 2021-01-22 08:19

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\

相关标签:
4条回答
  • 2021-01-22 09:09

    Use the Thread.sleep function to pause execution.

    System.out.print("H");
    Thread.sleep(1000);
    System.out.print("E");
    ...etc
    

    Of course, you'd probably want to put all of that into a loop, but Thread.sleep is what you want

    0 讨论(0)
  • 2021-01-22 09:18

    Try this:

     try {
      Thread.sleep(timeInMiliseconds); // In your case it would be: Thread.sleep(100);
    } catch (Exception e) {
        e.printStackTrace();
    }
    
    0 讨论(0)
  • 2021-01-22 09:23
    String text = "Hello";
    
    for(int i=1; i<=text.length();i++){
       System.out.println(text.substring(0, i));
        try {
           Thread.sleep(100); 
        } catch (Exception e) {
           e.printStackTrace();
        }
    }
    

    Edit: if you want only 1 character by 1, than:

    for(int i=0; i<text.length();i++){
       System.out.print(""+text.characterAt(i));
        try {
           Thread.sleep(100); 
        } catch (Exception e) {
           e.printStackTrace();
        }
    }
    
    0 讨论(0)
  • 2021-01-22 09:25

    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);
        }
    }
    
    0 讨论(0)
提交回复
热议问题