Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java Hangman分配和循环条件_Java_Arrays_Loops_For Loop_While Loop - Fatal编程技术网

Java Hangman分配和循环条件

Java Hangman分配和循环条件,java,arrays,loops,for-loop,while-loop,Java,Arrays,Loops,For Loop,While Loop,我有一个JAVA任务,我必须使用数组和循环创建一个Hangman程序 user1输入有效的单词(无数字或符号) 用户2可以尝试一次猜出整个单词,或者在总共10次尝试中使用一个字母进行猜测。最初,用户2必须按1来猜单词,或按2来选择字母。我改变了这一点,因为我认为这更方便用户 user2可以在任何时间点尝试猜测单词 程序需要检查user2的输入是否有效 必须是字母字符,而不是符号 必须仅为1个字符长度或与要猜测的单词相同的长度) 字母字符不能使用两次 如果user2的输入无效(上述条件),

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

  • user1输入有效的单词(无数字或符号)
  • 用户2可以尝试一次猜出整个单词,或者在总共10次尝试中使用一个字母进行猜测。最初,用户2必须按1来猜单词,或按2来选择字母。我改变了这一点,因为我认为这更方便用户
  • user2可以在任何时间点尝试猜测单词
程序需要检查user2的输入是否有效

  • 必须是字母字符,而不是符号
  • 必须仅为1个字符长度或与要猜测的单词相同的长度)
  • 字母字符不能使用两次
如果user2的输入无效(上述条件),它将给出错误消息并要求user2输入其他内容。任何无效输入都不计入10次尝试

现在,如果输入无效(上面的前两个条件),代码的行为应该是正确的。它会给出适当的错误消息,尝试次数不会增加

然而,我似乎无法编写这样一个条件:如果已经选择了一个字母,那么它也会给出一条错误消息并要求另一个字母

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

我觉得我必须在某个地方做一个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.
    }

}

}
import java.util.Scanner;
导入java.util.regex.Pattern;
公开课考试{
公共静态void main(字符串[]args){
char[]大写字母={'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'};//要显示给用户的字母表数组2。
字符串字串;
字符选择;
字符串userChoiceString;
字符串字数组字符串;
做{
System.out.println(“请输入一个有效单词(仅限字母)”;//向user1请求一个有效单词
Scanner wordInput=新扫描仪(System.in);
wordtoGuess=wordInput.next();
wordtoGuess=wordtoGuess.toUpperCase();
}while(Pattern.matches(“[A-Z]+”,wordtoGuess)==false);//检查单词是否有效
char[]wordArray=wordtoGuess.toCharArray();//将单词放入字符数组
char[]guessingWordArray=新字符[wordtoGuess.length()];
for(int h=0;h1//如果输入的长度与整个单词的长度不同,但超过1个字符,则出错
&&userChoiceString.length()for (int k = 0; k < upperAlphabet.length; k++) { // A used letter is replaced by * in alphabet array.
    if (letterChoice == upperAlphabet[k]) {
        upperAlphabet[k] = '*';
    }
}
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.
}
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.
    }

}

}