【发布时间】:2015-12-10 23:11:49
【问题描述】:
我在尝试制作刽子手游戏时遇到了一个小问题。我之前发表过一篇关于另一个错误的帖子,但现在我遇到了一个我无法弄清楚的新错误。我正在尝试验证字母猜测是否尚未输入。但它跳过了 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?
这只是说当数组中有一个空元素时,字母已经被猜到了。我在这里遗漏了什么吗?
【问题讨论】:
-
if (guesses[i] != finalGuess) { } else { "Letter already guessed, try again! "}很清楚。如果你想控制一个“空”(什么是空?)元素,那么你必须为它添加一个条件。 -
@m0skit0 当我提示用户输入猜测时,我有它,所以它将把它放入 char 值数组中。这不是我在这里做的吗?