简体   繁体   中英

I cannot get my printWithDelay method to print faster than 300 milliseconds.

Here is my method

public static void printWithDelay(String data, long delay) {
    for (char c : data.toCharArray()) {
        try {
            Thread.sleep(delay);
            System.out.print(c);
        } catch (InterruptedException e) {}
    }
    System.out.println();
}

So if i try to run the method with a given String, it will work at 300 milliseconds, but that is a bit too slow. I want it to run kinda like in the old pokemon games where it was printed fairly fast..

If i try to change it to under 300 milliseconds pr char, the output will just stand still until the whole String has been constructed, and then it will print the String..

Please help as this really annoys me /:

The interval we pass in Thread.sleep(long millis) method is in millis, I ran the above code in my Eclipse with Java 8 , character gets printed as per the interval specified, even if I reduce the interval to 10 it printed the character one by one.

What is the interval you tried?

You can try putting your loop inside the try { }.

    try {
        for (char c : data.toCharArray()){
             Thread.sleep(delay);
             System.out.print(c);
        }
    } catch (InterruptedException e) {}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM