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

如何在Java版Hangman游戏中限制猜测次数

Adding Guess Limit to Your Java Hangman Game

Hey there! Let's get that 15-guess limit added to your Hangman game smoothly. I'll walk you through the key changes and share the full modified code so you can drop it in and test right away.

Key Modifications Needed

  • Track remaining guesses with a variable initialized to 15
  • Update the loop condition to stop when guesses run out or the game is won
  • Notify the user of remaining guesses on each turn, and specifically when they guess wrong
  • Trigger a game-over message when guesses are exhausted

Modified Full Code

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;

public class Hangman {
    public static void main(String[] args) throws FileNotFoundException {
        // Load words from file (keep your existing logic here)
        File wordFile = new File("words.txt");
        Scanner fileScanner = new Scanner(wordFile);
        ArrayList<String> wordList = new ArrayList<>();
        
        while (fileScanner.hasNext()) {
            wordList.add(fileScanner.nextLine().toLowerCase());
        }
        fileScanner.close();
        
        String secretWord = wordList.get((int) (Math.random() * wordList.size()));
        
        // Game state initialization
        char[] guessedProgress = new char[secretWord.length()];
        for (int i = 0; i < guessedProgress.length; i++) {
            guessedProgress[i] = '_';
        }
        
        boolean isGameWon = false;
        int remainingGuesses = 15; // Set max guesses to 15
        Scanner userInputScanner = new Scanner(System.in);

        // Loop runs until game is won OR guesses are used up
        while (!isGameWon && remainingGuesses > 0) {
            // Display current game status
            System.out.println("\nCurrent word: " + String.valueOf(guessedProgress));
            System.out.println("Remaining guesses: " + remainingGuesses);
            System.out.print("Enter a single letter to guess: ");
            
            char userGuess = userInputScanner.nextLine().toLowerCase().charAt(0);
            boolean guessWasCorrect = false;

            // Check if the guessed letter is in the secret word
            for (int i = 0; i < secretWord.length(); i++) {
                if (secretWord.charAt(i) == userGuess) {
                    guessedProgress[i] = userGuess;
                    guessWasCorrect = true;
                }
            }

            // Handle wrong guesses
            if (!guessWasCorrect) {
                remainingGuesses--;
                System.out.println("Oops, wrong guess! Remaining guesses: " + remainingGuesses);
                
                // Trigger game over if no guesses left
                if (remainingGuesses == 0) {
                    System.out.println("\nGame Over! You've used all 15 guesses.");
                    System.out.println("The secret word was: " + secretWord);
                }
            }

            // Check if the player has guessed the full word
            isGameWon = String.valueOf(guessedProgress).equals(secretWord);
            if (isGameWon) {
                System.out.println("\nCongratulations! You won! The word was: " + secretWord);
            }
        }
        
        userInputScanner.close();
    }
}

What Changed?

  1. Added Guess Tracking: The remainingGuesses variable starts at 15 and decreases by 1 every time the user guesses incorrectly.
  2. Updated Loop Condition: The game loop now stops if either the player wins or runs out of guesses, preventing infinite loops once the limit is hit.
  3. User Feedback: Players see their remaining guesses on every turn, and get a clear message when they guess wrong. When guesses hit 0, the game ends and reveals the secret word.
  4. Seamless Integration: All your existing word-loading and core game logic stays intact—we just layered the guess limit on top.

If you have extra logic (like handling non-letter inputs or duplicate guesses), you can add checks for those too (e.g., verifying the input is a single character, or tracking already guessed letters to avoid penalizing repeat guesses).

内容的提问来源于stack exchange,提问作者Proximus Seraphim Dimitri Davi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 03:41:40