如何停止游戏结束时提示的剩余时间
嗨,我是Java的新手,我正在做功课,以创建包含三个级别的数字猜谜游戏。每个级别都会提示用户剩余时间,而他只有3次尝试。我尚未编码其他级别,因为我想先解决第一级别的时间。问题是即使游戏已经结束,时间(以秒为单位)仍会持续提示。
此外,我打算在代码的2级末尾放置一个while循环,这是个好主意吗? ...谢谢。
import java.util.*;
public class Random1 {
int sec = 0;
TimerTask task;
public Random1() {
this.task = new TimerTask() {
public void run() {
sec++;
if (sec == 10) {
System.out.println("\t 45 seconds Left!");
} else if (sec == 45) {
System.out.print("\n Times Up!");
System.out.println("\n Game Over !");
task.cancel();
System.out.print("\n Thank You For Playing :) ");
}
}
};
Timer mytimer = new Timer();
mytimer.scheduleAtFixedRate(task, 1000, 1000);
}
static int count = 0;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Random dice = new Random();
Random1 t = new Random1(); // called to apply timer
int number = 1 + dice.nextInt(6);
System.out.println();
System.out.println("Number is: " + number);
System.out.println("I am thinking of numbers 1 to 6. Guess which number is it?");
int myAnswer = input.nextInt();
if (myAnswer == number) {
System.out.println("Correct! You're a mind reader!");
count++;
} else if (myAnswer > number) {
System.out.println("Wrong! Too high. The number was " + number + ".");
count++;
}
else {
System.out.println("Wrong! Too low. The number was " + number + ".");
count++;
}
System.out.println("Number of trys: " + count);
if (count == 3 && myAnswer != number) {
System.out.println("You've reached the maximum trys. Goodbye!");
} else if (count < 3 && myAnswer != number) {
main(new String[] { "I am thinking of numbers 1 to 6. Guess which number it is?" });
} else if (count <= 3 && myAnswer == number) {
System.out.println("Congratulations! You're up for round 2 :) ");
}
}
}
答案 0 :(得分:0)
您应该打开“ mytimer”作为全局变量。 并应写:-
if (count == 3 && myAnswer != number)
{
System.out.println("You've reached the maximum trys. Goodbye!");
mytimer.cancel();
}
为我工作!
希望会有所帮助。