-2

Basically, I want to print characters with a delay between them. If I'm printing "test" it should go, "" "t" "te" "tes" "test". Presently, I'm using Thread.sleep(), but when used in rapid succession, it just kind of waits until the whole string is printed and then shows it. It goes "", waits and then suddenly says "test", basically. The way I want this to work is similar to how time.sleep() works in Python. Is there anything like that I can do in Java?

Miri
  • 1
  • 2
    This is nothing to do with Sleep, but is to do with how you do the output. System.out is by default line-buffered. You need a flush before every sleep if you want to see what has been written so far. – passer-by Jan 26 '22 at 23:04

1 Answers1

-2
public static void printCharacters(final String s) {
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            System.out.println("");
            try {
                for (char c : s.toCharArray()) {
                    Thread.sleep(1000);                     
                    System.out.println(c);
                } 
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };
    new Thread(runnable).start();
}
public static void main(String[] args) {
    printCharacters("Test");
}
Ryan
  • 1,762
  • 6
  • 11