我正在为学校开发这个 Hangman 程序,当用户猜错字母时,我无法正确打印错误猜测的数量。这是我到目前为止得到的代码,我将不胜感激任何提示。
import java.util.Scanner;
public class HangmanTest {
public static void main(String[] args) {
String[] wordBank = { "madelynn", "crystal", "mcbride", "daughter",
"adorable", "beautiful", "andrew", "programming", "alyssa",
"computers", "mcbreezy", "maddy", "happy", "vacation", "beach",
"java", "benefical", "military", "veteran", "standale",
"lions", "tigers", "redwings", "pistons", "michigan",
"football", "baseball", "hockey", "basketball", "golf" };
int minimum = 0;
int maximum = wordBank.length - 1;
String again;
do {
int choice = minimum + (int) (Math.random() * maximum);
String word = wordBank[choice];
// Converts the random word to asterix
String userWord = "";
for (int i = 0; i < word.length(); i++) {
userWord += "*";
}
// Breaks into a bunch of characters
char[] userWordCh = userWord.toCharArray();
// Show the random word
System.out.println("The word for you to guess is " + userWord);
// instantiate a scanner object
Scanner input = new Scanner(System.in);
int size = word.length();
int rightGuesses = 0;
int wrongGuesses = 0;
while (size != rightGuesses) {
System.out.println("Enter a character: ");
String response = input.next();
char ch = response.charAt(0);
char[] wordChars = word.toCharArray();
for (int i = 0; i < word.length(); i++) {
if (wordChars[i] == ch) {
userWordCh[i] = ch;
++rightGuesses;
} else {
++wrongGuesses;
}
} // end of for loop
System.out.print("The word is: ");
for (int j = 0; j < userWordCh.length; j++)
System.out.print(userWordCh[j]);
System.out.println();
} // end of while loop
System.out.println("You had " + wrongGuesses + " wrong guesses.");
System.out.println("Would you like to play again y/n: ");
again = input.next();
} while (again.equals("y"));
}
}
最佳答案
for (int i = 0; i < word.length(); i++) {
if (wordChars[i] == ch) {
userWordCh[i] = ch;
++rightGuesses;
} else {
++wrongGuesses;
}
} // end of for loop
在此循环中,每次猜测与单词中的字母匹配时,rightGuesses 都会增加 1,而每次猜测与单词中的字母不匹配时,rightGuesses 都会增加 1。正如您可以想象的那样,这将导致数字总体上增加与字母数量相同的数字,而它应该只增加一次。
尝试如下:
boolean foundMatch = false;
for (int i = 0; i < word.length(); i++) {
if (wordChars[i] == ch) {
userWordCh[i] = ch;
if (!foundMatch)
{
++rightGuesses;
foundMatch = true;
}
}
}
if (!foundMatch)
{
++wrongGuesses;
}
// end of for loop
现在我们只增加 rightGuesses 和rongGuesses 之一一次 - rightGuesses 仅在我们没有找到匹配项时才可以增加(将找到的匹配设置为 true),而 falseGuesses 只能在我们没有找到匹配项时增加一次。
关于java - 刽子手错误的猜测无法正确打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14739243/