Search code examples
javatextconsole-applicationdelay

Display characters with a delay in between each


I am working on a simple text based adventure game.

I would like to get the text to show up one character at a time.

I'm not really sure what that is called, but I would like for the text to show up as if you are seeing the words being typed out.

Can this be done without using Swing?


Solution

  • You can write yourself a helper method that prints one character from the string, then waits for some time, then prints the next character, etc.

    public void delayedPrint(int delay, String s) {
        try {
            for (char c : s.toCharArray()) {
                System.out.print(c);  // print characters without newline
                Thread.sleep(delay);  // wait for some milli seconds
            }
        } catch (InterruptedException e) {
        }
        System.out.println(); // finally, add a line break
    }
    

    Then just use this method whenever you want to print some text in this way:

    delayedPrint(100, "A long time ago, in a dungeon far far away...");