我在尝试制作一个刽子手游戏时遇到了一些问题。我之前发过关于其他错误的帖子,但现在我遇到了一个我无法弄清楚的新错误。我正在尝试验证字母猜测是否尚未输入。但它正在跳过if / else语句的整个部分。当我运行此代码时:
public class 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?
这只是说当数组中有一个空元素时,这个字母已经被猜到了。我在这里错过了什么吗?
答案 0 :(得分:2)
让我们通过您的示例遍历代码(我强烈建议您自己使用调试器):
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
循环的末尾。在处理之前,无需存储猜测。
答案 1 :(得分:0)
是。变量totalTries
最初为1.您可以阅读猜测,然后将guesses[totalTries - 1]
设置为猜测的字符,这意味着guesses[0]
等于finalGuess
。然后将i
从0循环到totalTries - 1
,这也是0.循环执行一次,并检查第一个条目不是finalGuess
。但事实是,我们只是设定它。
如果仅使用for循环来发现重复的猜测,您可以将第一个for循环中的条件更改为i < totalTries - 1
,它应该可以工作,但您需要在下面移动标记刽子手的单词。为了对代码产生最小的影响,请使用m0skit0的解决方案。