【发布时间】:2018-06-14 16:49:42
【问题描述】:
我对 Java 编码比较陌生,可以被视为新手。然而,我还有很多东西要学,我正在尝试创建一个带有倒计时和秒表的迷你乘法游戏。我希望秒表在倒计时说“开始!”后以秒和毫秒为单位计数。我想显示玩家解决问题花了多长时间。我尝试查找有关如何初始化秒表的教程,但是它似乎没有初始化。我知道这一点是因为我打印了值,secondsPassed 最后输出为 0。 谁能帮我修复我的代码,这样我就可以在“Go!”之后的几秒和几毫秒内启动一个计时器。并在游戏完成后显示时间? 谢谢。
import java.util.Scanner;
import java.util.Timer;
import java.util.TimerTask;
public class Mathgame {
public static int secondsPassed = 0;
Timer timer = new Timer();
TimerTask task = new TimerTask() {
public void run() {
secondsPassed++;
}
};
public void start() {
timer.scheduleAtFixedRate(task,1000,1000);
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Welcome to 'The Math Game!' Please chose whether you would like to play or not by inputting 'yes' or 'no'.");
String x = input.nextLine();
if(x.equals ("no")) {
System.out.println("Ok! Maybe next time!");
System.exit(1);
} else {
System.out.println("OK! We are starting the game in...");
System.out.println("3");
try {
Thread.sleep(1000);
} catch(InterruptedException ex){
System.exit(0);
}
System.out.println("2");
try {
Thread.sleep(1000);
} catch(InterruptedException ex) {
System.exit(0);
}
System.out.println("1!!");
try {
Thread.sleep(1000);
} catch(InterruptedException ex) {
System.exit(0);
}
System.out.println("Go!");
System.out.println("Your timer started!");
System.out.println(secondsPassed);
}
}
}
【问题讨论】:
-
你从来没有打电话给
start()? -
看,我不确定你的意思。请理解我是 Java 的新手。