尝试制作子手游戏时,我遇到了一个小问题。之前,我曾发表过一篇有关其他错误的文章,但现在我遇到了一个我不知道的错误。我试图验证尚未输入的字母猜测。但是它跳过了if / else语句的整个部分。当我运行此代码时:
公共类TestingStuff {
static StringBuffer randomWord;
static Scanner console = new Scanner(System.in);
static int totalTries = 1;
static String guess;
static char finalGuess;
public static void main(String[] args) throws Exception {
randomWord = TestingStuff.sendGet();
char[] guesses = new char[26];
int length = randomWord.length();
System.out.print("* * * * * * * * * * * * * * *"
+ "\n* Welcome to Hangman! *"
+ "\n* * * * * * * * * * * * * * *");
System.out.println("\nYou get 10 tries to guess the word by entering in letters!\n");
System.out.println(randomWord);
/*
Cycles through the array based on tries to find letter
*/
while (totalTries <= 10) {
System.out.print("Try #" + totalTries + "\nWord: " + makeDashes(randomWord));
//Right here: Search through the array of guesses, make it 26 characters to represent the alphabet
//if the user guess equals an already guessed letter, add to try counter. If it's correct, then reveal the letter that is
//correct and do it again without adding to the try counter.
System.out.print("\nWhat is your guess? ");
guess = console.nextLine();
finalGuess = guess.charAt(0);
guesses[totalTries - 1] = finalGuess; //Puts finalGuess into the array
for (int i = 0; i < totalTries; i++) { //checks to see if the letter is already guessed
if (guesses[i] != finalGuess) {
System.out.println(guesses[i]);
for (int j = 0; i < length; j++) { //scans each letter of random word
if (finalGuess == randomWord.charAt(j)) {
//put a method that swaps out dashes with the guessed letter
totalTries++;
}
}
} else {
System.out.println("Letter already guessed, try again! ");
}
}
}
}
我得到这样的输出:
* * * * * * * * * * * * * * *
* Welcome to Hangman! *
* * * * * * * * * * * * * * *
You get 10 tries to guess the word by entering in letters!
ostracization
Try #1
Word: -------------
What is your guess? a
Letter already guessed, try again!
Try #1
Word: -------------
What is your guess?
只是说当数组中有一个空元素时就已经猜到了字母。我在这里想念什么吗?
最佳答案
让我们看一下示例代码(强烈建议您使用调试器自己完成):
guesses[totalTries - 1] = finalGuess; // guesses[0] = 'a'
if (guesses[i] != finalGuess) // i = 0, guesses[0] = 'a', finalGuess = 'a'
else System.out.println("Letter already guessed, try again! ");
你可以移动
guesses[totalTries - 1] = finalGuess; //Puts finalGuess into the array
在最外面的
for
循环的末尾。在处理之前无需存储猜测。