You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java猜数字游戏结束后如何停止剩余时间提示?

解答你的猜数字游戏问题

Hey there! Let's work through your two questions step by step—first fixing that stubborn timer issue, then talking about your while loop plan for level 2.

一、解决计时器持续提示的问题

Right now, your timer only stops when the 45-second mark hits, but the game can end way earlier (like when you guess correctly or use up all 3 tries). That's why the timer keeps ticking and printing messages even after the game is over. Here's how to fix it:

  1. First, make the Timer a member variable of your Random1 class, and add a method to stop both the task and the timer cleanly:

    import java.util.*;
    public class Random1 {
        int sec = 0;
        TimerTask task;
        Timer mytimer; // 把Timer改成成员变量,方便外部控制
    
        public Random1() {
            this.task = new TimerTask() {
                public void run() {
                    sec++;
                    if (sec == 10) {
                        System.out.println("\t 35 seconds Left!"); // 这里你原来的提示有点小错误,sec=10时应该是剩35秒
                    } else if (sec == 45) {
                        System.out.print("\n Times Up!");
                        System.out.println("\n Game Over !");
                        stopTimer(); // 调用统一的停止方法
                        System.out.print("\n Thank You For Playing :) ");
                        System.exit(0); // 直接退出程序,避免后续逻辑混乱
                    }
                }
            };
            mytimer = new Timer();
            mytimer.scheduleAtFixedRate(task, 1000, 1000);
        }
    
        // 新增方法:停止计时器和任务
        public void stopTimer() {
            task.cancel();
            mytimer.cancel();
        }
    }
    
  2. Then, call this stopTimer() method in every scenario where the game ends early:

    • When the user guesses correctly:
      if (myAnswer == number) {
          System.out.println("Correct! You're a mind reader!");
          count++;
          t.stopTimer(); // 停止计时器
      }
      
    • When the user uses up all 3 tries:
      if (count == 3 && myAnswer != number) {
          System.out.println("You've reached the maximum trys. Goodbye!");
          t.stopTimer(); // 停止计时器
          System.exit(0); // 退出程序
      }
      

二、关于用while循环实现第二关卡的建议

This is a fantastic idea! Your current approach of recursively calling main() to handle multiple tries is really not ideal—it clutters the call stack, makes the logic harder to follow, and will get messy fast when you add more levels.

Using loops (either while or for) will make your code way cleaner and easier to maintain. Here's a quick outline of how to structure it:

  • Use an outer loop to handle the 3 levels
  • Use an inner loop for the 3 tries per level

Here's a simplified example of what that could look like:

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    Random dice = new Random();

    // 外层循环控制3个关卡
    for (int level = 1; level <= 3; level++) {
        System.out.println("\n=== Level " + level + " ===");
        Random1 t = new Random1(); // 每个关卡启动新的计时器
        int number = 1 + dice.nextInt(6);
        boolean levelWon = false;

        // 内层循环控制3次尝试
        for (int attempt = 1; attempt <= 3; attempt++) {
            System.out.println("I'm thinking of a number between 1 and 6. Guess it!");
            int myAnswer = input.nextInt();

            if (myAnswer == number) {
                System.out.println("Correct! You nailed it!");
                levelWon = true;
                t.stopTimer(); // 停止计时器
                break;
            } else if (myAnswer > number) {
                System.out.println("Wrong! Too high.");
            } else {
                System.out.println("Wrong! Too low.");
            }
            System.out.println("Attempts used: " + attempt);
        }

        if (levelWon) {
            System.out.println("Great job! Moving to Level " + (level + 1) + " :)");
        } else {
            System.out.println("You ran out of attempts. Game over!");
            t.stopTimer();
            break;
        }
    }
    System.out.println("Thanks for playing!");
    input.close();
}

This structure is way easier to tweak later—if you want to change the number range per level, adjust the number of tries, or add new rules, it'll be straightforward to modify.

内容的提问来源于stack exchange,提问作者Adaline Bowman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 09:01:50