我刚开始学习Java,这是我接触的第一种编程语言。
老师让我们使用while和for循环制作一个基本的Hangman游戏。
我的代码如下
当用户输入第一个猜测字符时,程序确实识别出了所猜测的字符,但仅在继续进行并声明我猜错字母!
非常感谢您的帮助!我的问题是,我的代码有什么问题?我需要程序告诉用户他的猜测是否正确。
我的代码:
import cs1.Keyboard;
public class Hangman {
public static void main(String args[]) {
int guessCount = 0;
int correctGuess = 0;
boolean foundIt;
boolean solved;
char guess, answer;
String word;
System.out.println("Welcome to HangMan!");
System.out.println("Please enter a word for the opponent to guess!");
word = Keyboard.readString();
while (guessCount <= 6) {
System.out.println("Please enter any letter A-Z as your guess!");
guess = Keyboard.readChar();
for (int i = 0; i < word.length(); i++) {
if (guess == word.charAt(i)) {
System.out.println("You have guessed a correct letter!");
correctGuess++;
System.out.println("Correct Guess Count: "
+ correctGuess);
solved = false;
}
else if (guess != word.charAt(i)) {
System.out.println("Sorry! That is an incorrect guess! "
+ "Please try again!");
guessCount++;
System.out.println("Guess Count: " + guessCount);
solved = false;
}
}
if (correctGuess == word.length()) {
solved = true;
System.out.println("Congratulations! " +
"You have guessed the word!");
}
}
}
}
这是我目前的进展,以下是输出结果。
Welcome to HangMan!
Please enter a word for the opponent to guess!
hello
Please enter any letter A-Z as your guess!
l
Sorry! That is an incorrect guess! Please try again!
Guess Count: 1
Sorry! That is an incorrect guess! Please try again!
Guess Count: 2
You have guessed a correct letter!
Correct Guess Count: 1
You have guessed a correct letter!
Correct Guess Count: 2
Sorry! That is an incorrect guess! Please try again!
Guess Count: 3
Please enter any letter A-Z as your guess!