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

Java猜数字游戏优化需求:新增菜单与5次猜测次数限制

Hey there! Let's get your number guessing game fully up and running with all the features you want. Below is a complete, commented Java implementation that includes the menu system, 5-guess limit, and all the core game logic:

Complete Number Guessing Game Code
import java.util.Scanner;
import java.util.Random;

public class NumberGuessingGame {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        boolean isRunning = true;

        // Main menu loop to keep program active until user exits
        while (isRunning) {
            System.out.println("\n=== Number Guessing Game ===");
            System.out.println("1. Start New Game");
            System.out.println("2. View Game Instructions");
            System.out.println("3. Exit");
            System.out.print("Enter your choice: ");
            
            int choice = scanner.nextInt();

            switch (choice) {
                case 1:
                    startNewGame(scanner);
                    break;
                case 2:
                    showInstructions();
                    break;
                case 3:
                    isRunning = false;
                    System.out.println("Thanks for playing! Goodbye.");
                    break;
                default:
                    System.out.println("Invalid choice! Please enter 1, 2, or 3.");
            }
        }
        scanner.close();
    }

    // Handles a single full game session with guess limit
    private static void startNewGame(Scanner scanner) {
        Random random = new Random();
        int targetNumber = random.nextInt(100) + 1; // Generate random number 1-100
        int remainingGuesses = 5;
        boolean hasGuessedCorrectly = false;

        System.out.println("\nNew game started! I'm thinking of a number between 1 and 100.");
        System.out.println("You have " + remainingGuesses + " guesses left.");

        // Game loop: runs until guesses are used up or correct number is found
        while (remainingGuesses > 0 && !hasGuessedCorrectly) {
            System.out.print("Enter your guess: ");
            int userGuess = scanner.nextInt();
            remainingGuesses--;

            if (userGuess == targetNumber) {
                hasGuessedCorrectly = true;
                System.out.println("Congratulations! You guessed the number in " + (5 - remainingGuesses) + " tries!");
            } else if (userGuess > targetNumber) {
                System.out.println("Too high!");
            } else {
                System.out.println("Too low!");
            }

            // Remind user of remaining guesses if game isn't over
            if (remainingGuesses > 0 && !hasGuessedCorrectly) {
                System.out.println("You have " + remainingGuesses + " guesses left.");
            }
        }

        // Show correct number if user runs out of guesses
        if (!hasGuessedCorrectly) {
            System.out.println("Sorry, you've run out of guesses! The number was " + targetNumber + ".");
        }
    }

    // Displays clear game rules for new players
    private static void showInstructions() {
        System.out.println("\n=== Game Instructions ===");
        System.out.println("- The computer will pick a random number between 1 and 100.");
        System.out.println("- You get 5 chances to guess the correct number.");
        System.out.println("- After each guess, you'll get a hint: 'Too high!' or 'Too low!'");
        System.out.println("- Guess correctly within 5 tries to win!");
        System.out.println("- Use the main menu to start a new game, view these rules, or exit.");
    }
}

Key Feature Breakdown

Let's walk through the parts you wanted to add:

1. Menu System

  • A while loop keeps the program running until the user selects "Exit".
  • A switch statement handles menu choices, directing users to start a game, view instructions, or close the program.
  • Invalid inputs trigger a friendly error message so the user knows to try again.

2. 5-Guess Limit

  • We initialize remainingGuesses to 5 at the start of each game.
  • Every guess decrements this count, and the game stops either when the user guesses correctly or uses all 5 tries.
  • If they run out of guesses, we reveal the correct number to keep the game fun and informative.

3. Game Instructions

  • The showInstructions helper function prints simple, easy-to-follow rules that players can reference anytime.

Learning Tips for Next Steps

Since you're a programming newbie, here are some great ways to build on this game:

  • Modify the code to let users choose a custom number range (like 1-50 or 1-200) instead of fixed 1-100.
  • Add a score tracker that counts how many games the user has won or lost.
  • Add input validation to handle non-number inputs (right now, entering a letter will crash the program—try using a try-catch block to fix this!).

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 08:52:54