0

Hangman配列とループを使用してプログラムを作成する必要がある Java の課題があります。

  • user1 は有効な単語を入力します (数字や記号は使用しないでください)
  • user2 は、単語全体を 1 回で推測するか、1 文字を使用して合計 10 回推測することができます。最初に、user2 は単語を推測するために 1 を押すか、文字を選択するために 2 を押す必要がありました。これはよりユーザーフレンドリーだと思うので、私はそれを変更しました。
  • user2 はいつでも単語の推測を試みることができます。

プログラムは、user2 の入力が有効であることを確認する必要があります

  • 記号ではなくアルファベットである必要があります
  • 1 文字の長さ、または推測する単語と同じ長さである必要があります)。
  • アルファベット文字を 2 回使用することはできません

user2 の入力が無効な場合 (上記の条件)、エラー メッセージが表示され、user2 に別の入力を求められます。無効な入力は、10 回の試行にはカウントされません。

今のところ、入力が無効な場合 (上記の最初の 2 つの条件)、コードは本来のように動作します。適切なエラー メッセージが表示され、試行回数は増えません。

ただし、文字が既に選択されている場合にエラー メッセージが表示され、別の文字を要求するという条件をコーディングすることはできないようです。

(if upperAlphabet[index] == '*', System.out.println("Duplicate. Try again"))最初の do/while ループにif 条件を入れようとしましたが、正しく動作しません。試行回数が増えます。

どこかで 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.
    }

}

}
4

3 に答える 3

1

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追加します。1 文字だけを推測した場合にのみ実行されることを確認してください。

boolean found = false;次に、その前とパーツfound = true;の内側に行を追加できifます。次に、ループの直後に の値をチェックし、foundまだ false の場合はメッセージを表示します。これは、ユーザーが推測を繰り返した場合に当てはまります。

do/while推測が ではない場合、ループを繰り返す方法を考え出す必要がありますfound。したがって、これは完全な答えではありませんが、やり直すには十分なはずです。

于 2013-11-07T18:49:24.783 に答える
0

したがって、David Wallace の回答を拡張するために、このコードの変更により、必要なことが行われるようになりました (ただし、彼が言及した追加の条件はまだ必要です)。

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. 

    int[] guessedLetters = new int[26];

    boolean guessed = false;

    for(int i=0;i<26;i++)
    {
        guessedLetters[i] = 0;
    }

    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 {

            guessed = false;

            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.");
            else 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."));
            for (int k = 0; k < upperAlphabet.length; k++) { // A used letter is replaced by * in alphabet array.
                if(guessedLetters[k] == 1)
                {
                    guessed = true;
                    System.out.println("You've already tried this letter. Please try again.");
                }
                if (letterChoice == upperAlphabet[k]) {
                    //upperAlphabet[k] = '*';
                    guessedLetters[k] = 1; //note which letter has been chosen
                }
            }
        } while (userChoiceString.length() != 1
                && userChoiceString.length() != wordtoGuess.length()
                || Character.isLetter(letterChoice) == false
                || guessed == true);

        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] = '*';
                    guessedLetters[k] = 1;
                }
            }
            */

            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.
    }

}

}
于 2013-11-07T20:04:23.593 に答える
0

あなたがやりたいことは、upperAlphabet の値を上書きする代わりに、見た文字をプッシュする別の配列を作成することです。

ArrayList<char> guessed = new ArrayList();
....
do{
  ...
while(//your conditions here
     && !guessed.contains(letterChoice) );
guessed.add(letterChoice));

次のようなものを使用して、通常の配列でもこれを行うことができます。

char guessed = new char[10];
do{
  ...
while(//your conditions here
      &&!contains(guessed, letterChoice));
add(guessed, letterChoice)

//supporting methods
public boolean contains(char[] arr, char val){
  //check that array has value
}

public void add(char[] arr, char val){
  //add val to first empty space in arr.
}
于 2013-11-07T18:49:42.030 に答える