2013-11-07 3 views
0

У меня есть назначение JAVA, где я должен создать программу Hangman с использованием массивов и циклов.Назначение коннектора и условия цикла

  • user1 вводит допустимое слово (без цифр или символов)
  • user2 может попытаться угадать слово целиком в одном кадре или угадать, используя одну букву в общей сложности 10 попыток. Первоначально пользователю2 приходилось нажимать 1, чтобы угадать слово или 2, чтобы выбрать букву. Я изменил это, так как считаю, что это более удобно.
  • Пользователь2 может попытаться угадать слово в любой момент времени.

Программа должна проверять входные данные, которые user2 является действительным

  • Должен быть алфавит символов, а не символ
  • Должен быть только 1 Длина символа или такой же длины, как слово в Угадай).
  • Алфавит символ не может быть использован дважды

Если вход в user2 недействителен (условия выше), он выдает сообщение об ошибке и просит user2 на вход что-то другое. Любой недопустимый ввод не учитывается в 10 попытках.

В настоящее время, если вход недействителен (первые 2 условия выше), код ведет себя так, как должен. Он дает соответствующее сообщение об ошибке, и количество попыток не увеличивается.

Однако, похоже, я не могу закодировать условие, в котором, если письмо уже выбрано, оно также выдает сообщение об ошибке и запрашивает другую букву.

Я пытаюсь установить условие (if upperAlphabet[index] == '*', System.out.println("Duplicate. Try again")) в первый цикл do/while, но он не работает должным образом: он увеличивает количество попыток.

У меня такое впечатление, что я должен что-то сделать для цикла. Не можете найти, где и как.

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

} 

} 
+0

Что вам нужно, это какое-то структуры данных, такой как «HashSet», чтобы сохранить догадки, которые уже сделал игрок, и проверить, находится ли догадка игрока уже в структуре. –

+0

Спасибо за предложение. Я нахожусь в классе новичка, поэтому мы еще не дотронулись до хэшета. – user2861118

+0

Похоже, ваш способ проверить, действительно ли письмо уже догадалось, работает. Сохранение массива символов и изменение одного на определенное специальное значение (*) должно работать, но это не самый эффективный способ, но я сомневаюсь, что начальный класс будет заботиться об эффективности. Посмотрите мой ответ ниже, если это то, с чем вы столкнулись. –

ответ

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 цикл, где вы запрашивая пользователя для входа. Убедитесь, что он работает только в том случае, если они угадывают только одного символа.

После этого вы можете добавить линию boolean found = false; и found = true; внутри части if. Затем сразу же после цикла проверьте значение found и покажите сообщение, если оно все еще ложно, что будет, если пользователь повторит предположение.

Вам все равно нужно разработать способ, чтобы цикл do/while повторялся, если угадать не found. Так что это не полный ответ, но этого должно быть достаточно, чтобы вы снова пошли.

+0

Благодарим за помощь! Я играл с кодом, и я решил (может быть, он неэффективен, но в любом случае), чтобы создать метод, который будет проверять массив upperAlphabet и посмотреть, все еще находится в массиве letterChoice. Я вызвал этот метод в основном коде и добавил условие «duplicateLetters (upperAlphabet, letterChoice) == -1» в первом цикле do/while. Кажется, работает! – user2861118

+0

Отлично. Это звучит как хороший способ сделать это. –

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

Так расширить ответ Дэвида Уоллеса, это modificiation вашего кода теперь делает то, что вы хотите (хотя она по-прежнему нуждается в дополнительном условии, что он упоминал):

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

} 

} 
Смежные вопросы