1

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

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?");
    }
}
4

3 回答 3

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?");
}
于 2016-01-25T20:56:24.593 回答
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);
}
于 2016-01-25T20:52:55.030 回答
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
于 2016-01-25T20:55:09.510 回答