2015-12-15 2 views
0

Цель этого кода - создать основную игру палача. Все работает отлично до последнего шага. После того, как пользователь угадает все буквы, которые он должен отображать "You guessed it", но цикл, кажется, выполняет одно дополнительное время. Я попытался сменить код цикла на:
while(guessedLetters < asteriskAmount - 1), но это просто закончило конец цикла слишком рано.
Любая помощь очень ценится.Hangman game in java без массивов

import java.util.Scanner; 

public class SecretPhrase { 
public static void main(String[] args) { 
    char userChoice; 
    String secretPhrase = "GO TEAM"; 
    Scanner input = new Scanner(System.in); 
    String hint = "G* T***"; 
    StringBuilder secretWord = new StringBuilder(hint); 

    System.out.println("The hint is " + hint); 

    System.out.println("Please guess a letter"); 
    userChoice = Character.toUpperCase(input.nextLine().charAt(0)); //Taking the input and turning to uppercase for comparing purposes 

    int asteriskAmount = hint.length() - 1; // "-1" for the space. 
    int guessedLetters = 2; // for the 'G' and the 'T' that are already displayed. 

    while(guessedLetters < asteriskAmount) { 
     boolean isInPhrase = checkLetter(userChoice, secretPhrase); 
     if(isInPhrase) { // if the guessed letter is a letter in the phrase... 
      int position = getPosition(userChoice, secretPhrase); 
      secretWord.setCharAt(position, userChoice); 
      hint = secretWord.toString(); 
      guessedLetters++; 
      System.out.println(secretWord); 
      System.out.println("Please guess a letter"); 
      userChoice = Character.toUpperCase(input.nextLine().charAt(0)); 
     } 
     else { 
      System.out.println("That letter is not in the phrase. Please try again >>> "); 
      userChoice = Character.toUpperCase(input.nextLine().charAt(0)); 
     } 
    } 
    System.out.println("You got it! The secret word is " + secretWord); 


} 
public static boolean checkLetter(char userChoice, String secretPhrase) { 
    boolean isInPhrase = false; 
    int amountOfLetters = 0; 
    for(int x = 0; x < secretPhrase.length(); x++) { 
     if(userChoice != secretPhrase.charAt(x)) { 
      isInPhrase = false; 
     } 
     else { 
      isInPhrase = true; 
      amountOfLetters++; 
     } 
    } 
    if(amountOfLetters >= 1) { 
     isInPhrase = true; 
    } 
    return isInPhrase; 
} 
public static int getPosition(char userChoice, String secretPhrase) { 
    int position; 
    int x = 0; 
    while(userChoice != secretPhrase.charAt(x)) { 
     x++; 
    } 
    position = x; 
    return position; 
} 
} 

Это мой выход:

The hint is G* T*** 
Please guess a letter 
**o** 
GO T*** 
Please guess a letter 
**e** 
GO TE** 
Please guess a letter 
**a** 
GO TEA* 
Please guess a letter 
**m** 
GO TEAM 
Please guess a letter 
**a** 
You got it! The secret word is GO TEAM 

ответ

0

Удалить эти строки из цикла до

System.out.println("Please guess a letter"); 
userChoice = Character.toUpperCase(input.nextLine().charAt(0)); 

Теперь внутри цикла, переместить те же строки в начале цикла. не

while(guessedLetters < asteriskAmount) { 
     System.out.println("Please guess a letter"); 
     userChoice = Character.toUpperCase(input.nextLine().charAt(0)); 
    boolean isInPhrase = checkLetter(userChoice, secretPhrase); 
    if(isInPhrase) { // if the guessed letter is a letter in the phrase... 
     int position = getPosition(userChoice, secretPhrase); 
     secretWord.setCharAt(position, userChoice); 
     hint = secretWord.toString(); 
     guessedLetters++; 
     System.out.println(secretWord); 
    } 
    else { 
     System.out.println("That letter is not in the phrase. Please try again >>> "); 
     userChoice = Character.toUpperCase(input.nextLine().charAt(0)); 
    } 
} 

Edit: Для того, чтобы проверить наличие нескольких экземпляров выбранного письма без использования массивов, попробуйте использовать это вместо вашего замены кода

for(int r=0; r<secretPhrase.length(); r++){ 
    if(secretPhrase.charAt(r) == userChoice){ 
     secretWord.setCharAt(r, userChoice); 
     guessedLetters++; 
    } 
} 

При этом, вы больше не нужен метод getPosition или position переменная.

полный цикл с предложенными изменениями

while(guessedLetters < asteriskAmount) { 
     System.out.println("Please guess a letter"); 
     userChoice = Character.toUpperCase(input.nextLine().charAt(0)); 
    boolean isInPhrase = checkLetter(userChoice, secretPhrase); 
    if(isInPhrase) { // if the guessed letter is a letter in the phrase... 
     for(int r=0; r<secretPhrase.length(); r++){ 
      if(secretPhrase.charAt(r) == userChoice){ 
       secretWord.setCharAt(r, userChoice); 
       guessedLetters++; 
      } 
     } 
     System.out.println(secretWord); 
    } 
    else { 
     System.out.println("That letter is not in the phrase. Please try again >>> "); 
     userChoice = Character.toUpperCase(input.nextLine().charAt(0)); 
    } 
} 
+0

Эй, спасибо за ваш ответ. Как заменить звездочки буквами, если есть несколько случаев без массивов? Я думал по строкам, вместо метода 'checkLetter', возвращающего' boolean', возможно, он может вернуть значение 'int', которое сообщает мне, сколько раз это письмо имеет место, а затем создайте какой-то цикл, который заменит звездочки с буквой. Любые другие предложения? – Jacob

+0

Извините, я не ответил раньше, я был в дороге. Я обновил свой ответ, чтобы добиться такого же результата без использования массивов. Посмотрите и посмотрите, что вы думаете :) –

+0

Большое вам спасибо за помощь. Я просто хотел указать, что вам нужно добавить '()' 'в' for (int r ...... length()) ' – Jacob

0

Проблема заключается в том, что вы всегда просят снова после того, как увеличивающиеся guessedLetters. Поэтому он всегда будет спрашивать одно дополнительное время. Попробуйте переупорядочить вещи, например:

//System.out.println("Please guess a letter"); 
//userChoice = Character.toUpperCase(input.nextLine().charAt(0)); //Taking the input and turning to uppercase for comparing purposes 

final int asteriskAmount = hint.length() - 1; // "-1" for the space. 
int guessedLetters = 2; // for the 'G' and the 'T' that are already displayed. 

while (guessedLetters < asteriskAmount) { 
    System.out.println(secretWord); 
    System.out.println("Please guess a letter"); 
    userChoice = Character.toUpperCase(input.nextLine().charAt(0)); 

    final boolean isInPhrase = checkLetter(userChoice, secretPhrase); 
    if (isInPhrase) { // if the guessed letter is a letter in the phrase... 
     final int position = getPosition(userChoice, secretPhrase); 
     secretWord.setCharAt(position, userChoice); 
     hint = secretWord.toString(); 
     guessedLetters++; 
    } else { 
     System.out.println("That letter is not in the phrase. Please try again >>> "); 
     userChoice = Character.toUpperCase(input.nextLine().charAt(0)); 
    } 

    System.out.println(guessedLetters); 
} 
0

Возьмите вход пользователя внутри цикла while. Что происходит, так это то, что в последнем цикле вы проверяете ввод пользователя, а затем запрашиваете другой пользовательский ввод в конце цикла. Игра пытается и заканчивается, но прежде чем она сможет закончить, она должна пройти через этот последний пользовательский ввод в while. Я всегда пытаюсь ввести свой пользовательский ввод в начале цикла, поэтому таких вещей не происходит. Надеюсь это поможет!

System.out.println("The hint is " + hint); 

//Move the 2 lines below inside your loop 
//System.out.println("Please guess a letter"); 
//userChoice = Character.toUpperCase(input.nextLine().charAt(0)); //Taking the input and turning to uppercase for comparing purposes 

int asteriskAmount = hint.length() - 1; // "-1" for the space. 
int guessedLetters = 2; // for the 'G' and the 'T' that are already displayed. 

while(guessedLetters < asteriskAmount) { 

    //Moved from above 
    System.out.println(secretWord); 
    System.out.println("Please guess a letter"); 
    userChoice = Character.toUpperCase(input.nextLine().charAt(0)); 

    boolean isInPhrase = checkLetter(userChoice, secretPhrase); 
    if(isInPhrase) { // if the guessed letter is a letter in the phrase... 
     int position = getPosition(userChoice, secretPhrase); 
     secretWord.setCharAt(position, userChoice); 
     hint = secretWord.toString(); 
     guessedLetters++; 

     //These are not needed any more 
     //System.out.println(secretWord); 
     //System.out.println("Please guess a letter"); 
     //userChoice = Character.toUpperCase(input.nextLine().charAt(0)); 
    }