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

Java Wordle项目do while循环终止逻辑实现求助

Fixing Your Java Wordle Loop Logic & Scanner Handling

Got it, let's get your Wordle-style game working correctly with the 5-guess limit and proper termination conditions. First, let's break down the issues in your original code:

  • Your counter variable was tracking invalid input (non-5-letter words) instead of actual guess attempts
  • There was no check to see if the user guessed the entire word correctly (so even if they got all letters right, the loop would keep running)
  • The target word tyler was re-declared every loop iteration (unnecessary)
  • The initial "Press enter to begin" was causing awkward input handling, as it would consume the first user's enter key press

Here's the revised code that fixes all these issues, plus adds clear, user-friendly feedback:

import java.util.Scanner;

class FinalProject {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        final String TARGET_WORD = "tyler"; // Move target word outside loop (constant for clarity)
        int attempts = 0;
        boolean isWordGuessed = false;

        do {
            // Get valid 5-letter guess from user (invalid inputs don't consume an attempt)
            String userInput;
            do {
                System.out.println("Enter your 5-letter guess (Attempt " + (attempts + 1) + "/5):");
                userInput = input.nextLine().toLowerCase(); // Normalize to lowercase for case-insensitive checks
            } while (userInput.length() != 5);

            // Convert strings to char arrays (simplified with built-in method)
            char[] guessChars = userInput.toCharArray();
            char[] targetChars = TARGET_WORD.toCharArray();

            // Check each character and give position-specific feedback
            System.out.println("\nGuess feedback:");
            boolean currentGuessIsCorrect = true;
            for (int i = 0; i < targetChars.length; i++) {
                if (guessChars[i] == targetChars[i]) {
                    System.out.println("Letter '" + guessChars[i] + "' at position " + (i + 1) + " is CORRECT!");
                } else {
                    System.out.println("Letter '" + guessChars[i] + "' at position " + (i + 1) + " is incorrect.");
                    currentGuessIsCorrect = false; // Mark this guess as not fully right
                }
            }

            // Check if the entire word was guessed
            if (currentGuessIsCorrect) {
                isWordGuessed = true;
                System.out.println("\nCongratulations! You guessed the word correctly!");
            } else {
                attempts++;
                System.out.println("\nThat's not the word. Try again!\n");
            }

        } while (attempts < 5 && !isWordGuessed); // Terminate if 5 attempts are used OR word is guessed

        // If loop ended because attempts ran out
        if (!isWordGuessed) {
            System.out.println("Game over! You've used all 5 attempts. The correct word was: " + TARGET_WORD);
        }

        input.close(); // Clean up the scanner resource properly
    }
}

Key Improvements Explained:

  • Proper Attempt Tracking: The attempts variable counts only valid 5-letter guesses, so typos with wrong word length don't waste a turn
  • Dual Termination Conditions: The do-while loop stops immediately if either the user uses all 5 attempts OR guesses the word correctly
  • Case Insensitivity: Added .toLowerCase() so guesses like "Tyler" or "TYLER" work the same as "tyler" (a nice quality-of-life tweak)
  • Simplified Char Arrays: Used toCharArray() instead of manual loops to convert strings to char arrays—cleaner and less error-prone
  • Clear User Feedback: Tells users which attempt they're on, gives position-specific feedback for each letter, and clearly announces win/loss states
  • Resource Cleanup: Added input.close() to properly close the Scanner and avoid resource leaks

This code will behave exactly as you need:

  • A) Stops and shows a loss message when the user uses all 5 attempts
  • B) Stops immediately and shows a win message when the user guesses "tyler" correctly

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 17:55:40