gpt4 book ai didi

Java - Hangman 游戏 - StringBuffer 变量上的 charAt 问题

转载 作者:行者123 更新时间:2023-11-29 04:54:42 26 4
gpt4 key购买 nike

所以我正在尝试使用一个返回随机单词的网站制作一个绞刑架游戏。我在刽子手游戏中使用了那个随机词。

我坚持的是验证用户的猜测。这是代码,我只是先将所有内容放在 main 中,然后再制作单独的方法来为我完成工作。

public static void main(String[] args) throws Exception {
randomWord = TestingStuff.sendGet();
int totalTries = 1;
char[] guesses = new char[26];
int length = randomWord.length();
Scanner console = new Scanner(System.in);

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);
System.out.print("\nWhat is your guess? ");
String guess = console.next();
char 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 (finalGuess != guesses[i]) {
for (int j = 0; i < length; j++) { //scans each letter of random word
if (finalGuess.equals(randomWord.charAt(j))) {

}
}
} else {
System.out.println("Letter already guessed, try again! ");
}
}
}
}

我坚持的是 while 循环内部,它说:

            for (int i = 0; i < totalTries; i++) { //checks to see if the letter is already guessed
if (finalGuess != guesses[i]) {
for (int j = 0; i < length; j++) { //scans each letter of random word
if (finalGuess.equals(randomWord.charAt(j))) {

}
}
} else {
System.out.println("Letter already guessed, try again! ");
}
}

它给我一个错误提示“char cannot be dereferenced”。我在这里错过了什么吗?

最佳答案

finalGuess 是原始 char - 您不能在其上使用方法,例如 equals。您可以使用 == 运算符比较两个 char:

if (finalGuess == randomWord.charAt(j)) {

关于Java - Hangman 游戏 - StringBuffer 变量上的 charAt 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34208475/

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