I have been trying to get a program writen in java to output text letter by letter with a pause in between each letter. The code word-wraps a string and prints it. My delay method "slow()" works well when the delay is half a second or a second, but at lower delay times it does some weird things.
When printing and the delay is extra short, the program hangs on that line for the delay times the number of letters being printed before the line return and then spits everything out at once.
Also when the delay is set to 250 milliseconds the text also prints out incorrectly.
In the example the string is:
"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla vitae molestie leo, sed molestie turpis."
The expected output would be:
Lorem ipsum dolor sit amet, consectetur adipiscing
elit. Nulla vitae molestie leo, sed molestie turpis.
But the output at 250 is:
Lrem ipsum dolrst aet, conseteur adipiscing
elit. ulla vitae olestie lo sed oleste turis.
Here's the code:
public static void main(String[] args) {
String x = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla vitae molestie leo, sed molestie turpis.";
say(500,x); // Works Nicely, does one letter at a time with a 0.5s wait in between.
System.out.println();
say(250,x); // Has proper delay, but prints strange stuff
System.out.println();
say(100,x); // Prints Line by line with a wait of (letters*0.1s) wait in between.
}
public static void say(int speed, String words) {
int i = 0;
int ii = 0;
while (i < words.length()) {
slow(speed);
System.out.print("" + words.charAt(i));
if (ii >= 50 && words.charAt(i) == ' ') {
System.out.println(words.charAt(i));
ii = 0;
} else {
ii++;
}
i++;
}
System.out.println(" ");
}
public static void slow(int time) {
try {
Thread.sleep(time);
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
Alternate slow()
method with same glitches:
public static void slow(int time) {
long startTime = System.currentTimeMillis();
while(System.currentTimeMillis() - startTime < time) {
}
}
I'm not sure if it's important, but this is all done in NetBeans 7.4 x64 with JDK 1.7.
I am new to Java, but not new to programming. Any help would be appreciated! The main problem is the timing, that is what I need to work; The weird printing is just a question why.
This smells fishy.. Your code looks good and works just fine for me, having run it from the command line. I think, like Jim Garrison said, this has to do with your environment. Have you tried running your program from the command line so as to leave Netbeans out of it?
The next thing I would suspect is the line Thread.currentThread().interrupt();
in your catch(InterruptedException ex)
block. Try commenting that out (and doing nothing except maybe printing the InterruptedException
stack trace (ex.printStackTrace()
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With