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\
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
Try this:
try {
Thread.sleep(timeInMiliseconds); // In your case it would be: Thread.sleep(100);
} catch (Exception e) {
e.printStackTrace();
}
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();
}
}
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);
}
}