Reputation: 85
using this code at the minute which I found on the net
String welcome = "Would you like to play a game?";
for (int i = 0; i < welcome.length(); i++) {
System.out.println(welcome.charAt(i));
}
Pretty basic stuff, but it prints out really quickly and line by line, how can i add a small pause, and print immediately after the previous character? So by the end it just says Would you like to play a game?
Im working in CMD, and Sublime text.
Thanks!
Upvotes: 3
Views: 1500
Reputation: 96424
Use System.out.print instead of println. Use Thread.sleep to pause. Loop until the whole string is printed out.
String welcome = "Would you like to play a game?";
for (int i = 0; i < welcome.length(); i++) {
System.out.print(welcome.charAt(i));
Thread.sleep(1000L); // in milliseconds
}
System.out.println(); // start a new line
Thread.sleep throws InterruptedException. If this code goes in your main method, the easiest way to handle it (assuming you have no interest in canceling the thread by interrupting it) is to add throws InterruptedException
to the main method declaration (the exception will not get thrown, you're just keeping the compiler happy).
Upvotes: 5
Reputation: 30032
for (int i = 0; i < welcome.length(); i++) {
System.out.print(welcome.charAt(i));
Thread.sleep(100);
}
Upvotes: 1
Reputation: 14035
Use System.out.print
instead of System.out.println
. To add a small delay the easiest thing is to use Thread.sleep
.
Upvotes: 2