gpt4 book ai didi

Java - 制作刽子手游戏

转载 作者:行者123 更新时间:2023-12-02 04:06:46 26 4
gpt4 key购买 nike

我在尝试制作刽子手游戏时遇到了一个小问题。我之前发表过一篇关于不同错误的文章,但现在我遇到了一个我无法弄清楚的新错误。我正在尝试验证字母猜测是否尚未输入。但它跳过了 if/else 语句的整个部分。当我运行此代码时:

公共(public)类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 循环的末尾。在处理之前无需存储猜测。

关于Java - 制作刽子手游戏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34213468/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com