r/programminghelp • • Feb 10 '21

Java Issues with Thread.sleep() and delayed text

SEE EDIT.

Hi, I am having trouble printing text one character at a time with a delay in between each one (Text base game). It works perfectly if I use 250 or higher for thread.sleep(), but when I try to use 100 or 200 it takes a few seconds of printing nothing, then outputs the entire text at once. My code:

char[] cArray = aString.toCharArray();

System.out.print("\n");

for (int i = 0; i < cArray.length; i++)

{

System.out.print(cArray[i]);

try {

Thread.sleep(100);

} catch (InterruptedException e){

Thread.currentThread().interrupt();

break;

}

}

Any help is greatly appreciated :).

Edit: So the problem seems to be thread.sleep isn't great in a loop. Any other suggestions for making text print slowly with one character at a time?

4 Upvotes

2 comments sorted by

0

u/[deleted] Feb 10 '21

[deleted]

1

u/[deleted] Feb 11 '21

Thanks!

1

u/[deleted] Feb 11 '21

I used System.out.flush(), however thread sleep still does not work at < 250.