新手编程作业:验证输入单词与随机生成字母集的匹配性及实现回合制游戏循环的方法问询
Hey there! Let's tackle your Boggle-style game problems one by one—they're totally solvable, so let's dive in.
To verify that a player's word only uses characters from your random letter set (and doesn't use any character more times than it appears), you can use a character count approach. Here's how to implement it:
Step 1: Count Occurrences of Each Generated Letter
First, create a count of how many times each letter appears in your letters array. Since we're dealing with lowercase letters (you can convert inputs to lowercase to handle case insensitivity), an array of size 26 works perfectly:
// After generating your letters array int[] letterCounts = new int[26]; // Index 0 = 'a', 1 = 'b', ..., 25 = 'z' for (char c : letters) { // Convert the character to its corresponding index (e.g., 'a' becomes 0) letterCounts[c - 'a']++; }
Step 2: Validate the Player's Word
Create a helper method that checks if the player's word can be formed using the counted letters. We'll make a copy of the count array so we don't modify the original (since we'll need it for future validations):
import java.util.Arrays; // Don't forget this import for Arrays.copyOf public boolean isWordValid(String playerWord, int[] originalLetterCounts) { // Make a copy of the counts to modify during validation int[] tempCounts = Arrays.copyOf(originalLetterCounts, originalLetterCounts.length); String lowerCaseWord = playerWord.toLowerCase(); // Handle uppercase inputs for (char c : lowerCaseWord.toCharArray()) { int charIndex = c - 'a'; // Double-check the character is a letter (though you already validated this earlier) if (charIndex < 0 || charIndex >= 26) { return false; } // If we have no more of this letter left, the word is invalid if (tempCounts[charIndex] == 0) { return false; } // Decrement the count for this letter (we've used one instance) tempCounts[charIndex]--; } // If we made it through all characters, the word is valid against the letter set return true; }
How to Use This
After validating that the player's input has only letters, call this method. If it returns true, you can then check if the word is in your preset short word list. If either check fails, assign a score of 0:
// Inside your player input logic if (p1Answer.matches("^[a-zA-Z]*$")) { System.out.println("Player 1's answer is: " + p1Answer); boolean isLetterValid = isWordValid(p1Answer, letterCounts); boolean isInWordList = yourWordList.contains(p1Answer.toLowerCase()); // Assume yourWordList is a Set<String> for fast lookups if (isLetterValid && isInWordList) { // Assign score based on word length or your rules } else { JOptionPane.showMessageDialog(null, "Invalid word—either uses letters not in the set or isn't in the word list! Score: 0"); } } else { JOptionPane.showMessageDialog(null, "Your answer contains invalid characters. NO SOUP FOR YOU!"); }
You’re right to consider a do-while loop here—this is exactly the scenario it’s designed for!
forloops work best when you know the exact number of iterations ahead of time (e.g., "run 5 rounds").do-whileloops are perfect when you want to run the code at least once, then ask the user if they want to continue. This matches your game’s "play a round, then choose to play again" flow perfectly.
Implementing the do-while Loop
Wrap your existing round logic inside a do-while block, and add a confirmation dialog at the end to check if players want another round:
import java.util.Arrays; // For printing the letters array correctly boolean playAgain; do { // Generate new letters for the round letters = Instantiable.getLetters(); JOptionPane.showMessageDialog(null, "Your random letters will be displayed"); System.out.println(Arrays.toString(letters)); // Fix: print the actual letters array, not the 'random' variable // Player 1 input and validation JOptionPane.showMessageDialog(null, "Please enter a word"); String p1Answer = JOptionPane.showInputDialog("Player 1, your answer"); if (p1Answer == null) { // Handle if the user clicks "Cancel" break; } if (p1Answer.matches("^[a-zA-Z]*$")) { System.out.println("Player 1's answer is: " + p1Answer); // Add your isWordValid and word list checks here } else { JOptionPane.showMessageDialog(null, "Your answer contains invalid characters. NO SOUP FOR YOU!"); } // Player 2 input and validation String p2Answer = JOptionPane.showInputDialog("Player 2, your answer"); if (p2Answer == null) { break; } if (p2Answer.matches("^[a-zA-Z]*$")) { System.out.println("Player 2's answer is: " + p2Answer); // Add validation checks here too } else { JOptionPane.showMessageDialog(null, "Your answer contains invalid characters. NO SOUP FOR YOU!"); } // Ask if players want another round int userChoice = JOptionPane.showConfirmDialog( null, "Would you like to play another round?", "Play Again?", JOptionPane.YES_NO_OPTION ); playAgain = (userChoice == JOptionPane.YES_OPTION); } while (playAgain); // Exit message when the game ends JOptionPane.showMessageDialog(null, "Thanks for playing!");
This setup ensures the first round runs automatically, and players get to choose whether to keep going after each round. No need to worry about "choosing the wrong loop"—do-while is the perfect fit here.
内容的提问来源于stack exchange,提问作者LosBluefist

