在文本显示之间暂停

时间:2016-01-25 20:44:52

标签: java sleep pause

所以我正在创建一个基于文本的游戏,我很难找到一种在文本显示之间暂停的方法..我知道线程睡眠会起作用,但我不想要为数百行文本执行此操作。这就是我所拥有的,但有更简单的方法吗?

public class MyClass {
    public static void main(String[] args) {
        System.out.println("Hello?");
        //pause here
        System.out.println("Is this thing on?");
        /**Obviously I have a pause here, but I dont want to have to use this every time.*/
        try {
            Thread.sleep(x);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("Now, what is your name?");
    }
}

3 个答案:

答案 0 :(得分:1)

为什么不简单地将它包装在另一个类中?

class DisplayWrapper {
    private final static long DEFAULT_PAUSE_MS = 250;

    public static void outputWithPause(String text, long ms) {
        System.out.println(text);
        try {
            Thread.sleep(ms);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void show(String text) {
        outputWithPause(text. DEFAULT_PAUSE_MS);
    }
}

public class MyClass {
public static void main(String[] args) {
    DisplayWrapper.show("Hello?");
    DisplayWrapper.show("Is this thing on?");
    DisplayWrapper.show("Now, what is your name?");
}

答案 1 :(得分:0)

查看TimerTask

你可以像这样使用它:

public static void main(String[] args) {
    Timer timer = new Timer();
    writeIn(timer, 3000, "Hello?");
    writeIn(timer, 6000, "Is this thing on?");
    writeIn(timer, 12000, "Now, what is your name?");
    closeTimerIn(timer, 13000); // clean exit
}

private static void writeIn(Timer timer, final int millis, final String text){
    TimerTask task = new TimerTask() {
        @Override
        public void run() {
            System.out.println(text);
        }
    };
    timer.schedule(task, millis);
}

private static void closeTimerIn(final Timer timer, final int millis){
    TimerTask task = new TimerTask() {
        @Override
        public void run() {
            timer.cancel();
        }
    };
    timer.schedule(task, millis);
}

答案 2 :(得分:0)

正如m.antkowicz在评论中提到的那样,你需要创建一个打印方法。我举了一个例子:

void printAndSleep(String string, int sleepTimeMs) {
  System.out.println(string);
  Thread.sleep(sleepTimeMs);
}

现在,只要您想要打印,只需使用我们上面制作的printAndSleep方法即可。像这样:

printAndSleep("Hello?", 1000); // Print and pause for 1 second
printAndSleep("Is this thing on?", 2000); // Print and pause for 2 seconds