Цель этого кода - создать основную игру палача. Все работает отлично до последнего шага. После того, как пользователь угадает все буквы, которые он должен отображать "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
Эй, спасибо за ваш ответ. Как заменить звездочки буквами, если есть несколько случаев без массивов? Я думал по строкам, вместо метода 'checkLetter', возвращающего' boolean', возможно, он может вернуть значение 'int', которое сообщает мне, сколько раз это письмо имеет место, а затем создайте какой-то цикл, который заменит звездочки с буквой. Любые другие предложения? – Jacob
Извините, я не ответил раньше, я был в дороге. Я обновил свой ответ, чтобы добиться такого же результата без использования массивов. Посмотрите и посмотрите, что вы думаете :) –
Большое вам спасибо за помощь. Я просто хотел указать, что вам нужно добавить '()' 'в' for (int r ...... length()) ' – Jacob