java - Hangman 赋值和循环条件

标签 java arrays loops for-loop while-loop

我有一个 JAVA 作业,必须使用数组和循环创建一个 Hangman 程序。

  • 用户1输入一个有效的单词(无数字或符号)
  • 用户2可以尝试一次猜出整个单词,或者使用一个字母总共猜10次。最初,用户 2 必须按 1 来猜测单词,或按 2 来选择字母。我改变了这一点,因为我认为这对用户更友好。
  • 用户2可以在任何时间点尝试猜测单词。

程序需要检查user2的输入是否有效

  • 必须是字母字符,而不是符号
  • 必须只有 1 个字符长度或与要猜测的单词长度相同)。
  • 一个字母字符不能使用两次

如果用户2的输入无效(上述条件),它会给出错误消息并要求用户2输入其他内容。任何无效输入都不会计入 10 次尝试。

目前,如果输入无效(上述前 2 个条件),代码将按其应有的方式运行。它会给出适当的错误消息,并且尝试次数不会增加。

但是,我似乎无法编写一个条件,如果已经选择了一个字母,它还会给出错误消息并要求输入另一个字母。

我尝试在第一个 do/while 中放入 if 条件 (if upperAlphabet[index] == '*', System.out.println("Duplicate. Try Again"))循环,但它无法正常工作:它增加了尝试次数。

我的印象是我必须在某个地方做一个 for 循环。找不到地点和方式。

import java.util.Scanner;
import java.util.regex.Pattern;

public class Test {

public static void main(String[] args) {

    char[] upperAlphabet = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I',
            'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U',
            'V', 'W', 'X', 'Y', 'Z' };  // Alphabet array to display to user2. 

    String wordtoGuess;
    char letterChoice;
    String userChoiceString;
    String wordArraytoString;

    do {
        System.out.println("Please enter a valid word (letters only)");   // Asks user1 for a valid word
        Scanner wordInput = new Scanner(System.in);
        wordtoGuess = wordInput.next();
        wordtoGuess = wordtoGuess.toUpperCase();
    } while (Pattern.matches("[A-Z]+", wordtoGuess) == false);     // Checks word is valid

    char[] wordArray = wordtoGuess.toCharArray();   // Puts word in character array               
    char[] guessingWordArray = new char[wordtoGuess.length()];
    for (int h = 0; h < guessingWordArray.length; h++) 
        guessingWordArray[h] = '*'; // Displays the word to guess with * for user2

    for (int i = 0; i < 20; i++) {  // Prints 20 empty lines to hide the input of the word from user1 
        System.out.println();
    }

    for (int j = 0; j < 10; j++) {   // 10 attempts loop

        do {

            System.out.print("Word to guess: ");
            System.out.println(guessingWordArray);
            System.out
                    .println("Please choose a letter or solve the word.    " // Asks for a letter or the whole word
                            + "Attempts left: " + (10 - j));
            System.out.println(upperAlphabet);
            Scanner userInput = new Scanner(System.in);
            userChoiceString = userInput.next();
            userChoiceString = userChoiceString.toUpperCase();    // Captures the input as a string
            letterChoice = userChoiceString.charAt(0);
            letterChoice = Character.toUpperCase(letterChoice);  // Captures the first letter of the input

            if (Character.isLetter(letterChoice) == false) // Error if input is an alphabet letter
                System.out.println("Invalid letter. Please try again.");
            if (userChoiceString.length() > 1 // Error if input is not the same length as the whole word but more than 1 character
                    && userChoiceString.length() < wordtoGuess.length())
                System.out.println(("Choose only one letter. Try again."));

        } while (userChoiceString.length() != 1
                && userChoiceString.length() != wordtoGuess.length()
                || Character.isLetter(letterChoice) == false);

        if (userChoiceString.length() == 1) { // if input is only 1 character

            for (int k = 0; k < upperAlphabet.length; k++) { // A used letter is replaced by * in alphabet array.
                if (letterChoice == upperAlphabet[k]) {
                    upperAlphabet[k] = '*';
                }
            }

            for (int m = 0; m < wordtoGuess.length(); m++) { // If a letter is correct, reveal the correct letter in the word to guess.
                if (letterChoice == wordArray[m]) {
                    guessingWordArray[m] = wordArray[m];
                }
            }
            wordArraytoString = new String(guessingWordArray); // If all letters are revealed in the word to guess, display winning message when count of guesses.
            if (wordArraytoString.equals(wordtoGuess)) {

                System.out.println(guessingWordArray);
                System.out.print("Congratulations.");
                System.out.print("You guessed the word: ");
                System.out.print(wordtoGuess);
                System.out.println(" in " + (j + 1) + " guesses.");
                break;

            }

        } else if (userChoiceString.length() == wordtoGuess.length()) { // If user2 tries to guess the whole word, displays winning message and number of guesses
            if (userChoiceString.equals(wordtoGuess)) {
                System.out.println(guessingWordArray);
                System.out.print("Congratulations.");
                System.out.print("You guessed the word: ");
                System.out.print(wordtoGuess);
                if (j == 0)
                    System.out.println(" in " + (j + 1) + " guess.");
                else
                    System.out.println(" in " + (j + 1) + " guesses.");
                break;
            } else
                System.out.println("Wrong guess. Please try again."); // If guessing word is wrong.
        }

        if (j >= 9)
            System.out
                    .println("You did not guess the word in the number of attemps allowed. Better luck next time."); // If exceeds 10 tries.
    }

}

}

最佳答案

您已经获得了数组 upperAlphabet,当用户进行猜测时您正在修改该数组。也许您可以安排一些事情,以便如果猜测超出了 upperAlphabet,系统会提示用户重复猜测。

你为什么不移动这个循环

for (int k = 0; k < upperAlphabet.length; k++) { // A used letter is replaced by * in alphabet array.
    if (letterChoice == upperAlphabet[k]) {
        upperAlphabet[k] = '*';
    }
}

do/while 循环中增加几行,提示用户输入。确保它仅在他们只猜出一个字符时运行。

然后,您可以在其前面添加行 booleanfound = false;,并在 if 部分内添加 found = true;。然后紧接着循环,检查 found 的值,如果仍然为 false,则显示一条消息(如果用户重复猜测,就会出现这种情况)。

如果没有找到猜测,您仍然需要找到一种方法来重复执行do/while循环。所以这不是一个完整的答案,但它应该足以让你再次前进。

关于java - Hangman 赋值和循环条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19843392/

相关文章:

java - 如何覆盖具有默认(包)可见性范围的方法?

python - 如果它们高于特定阈值,则将 numpy 数组元素设置为零

php - 如何循环访问关联数组值并将数据放入函数中

java - string.split() 方法的输出

java - 控制方法的访问

javascript - 使用javascript加入两个数据集

javascript - 对象实践中超出了最大调用堆栈大小

c++ - 识别 “Enter”

java - IF 语句检查(无法正常工作)

java - 如何中断 CompletableFuture 的底层执行