嘿伙计们我刚刚开始学习Java作为我的第一门编程语言! 在课堂上,我们被分配了一个基本的Hangman游戏,使用了一段时间和for循环!
到目前为止我有什么
当用户输入第一个猜测时,它确实识别出他/她猜到的字符已被纠正但只是继续并说明我猜错了字母!
非常感谢帮助!!我的问题是我在代码中做错了什么?我需要程序告诉用户他的猜测是对还是错。
我的代码:
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!
答案 0 :(得分:3)
您将guess
与String
中的每个字符进行比较,然后为每个字符显示消息。相反,您应该编写一个返回与输入匹配的字符数的方法(这也处理具有重复字母的单词)。所以,
private static int countOf(String in, char ch) {
int count = 0;
for (char c : in.toCharArray()) {
if (c == ch) {
count++;
}
}
return count;
}
然后你可以称之为,
guess = Keyboard.readChar();
int count = countOf(word, guess);
if (count > 0) {
System.out.println("You have guessed a correct letter!");
correctGuess += count;
} else {
System.out.println("Sorry! That is an inncorrect guess! Please try again!");
}
guessCount++;
修改要在没有第二种方法的情况下执行此操作,
guess = Keyboard.readChar();
int count = 0;
for (char c : in.toCharArray()) {
if (c == guess) {
count++;
}
}
if (count > 0) {
System.out.println("You have guessed a correct letter!");
correctGuess += count;
} else {
System.out.println("Sorry! That is an inncorrect guess! Please try again!");
}
guessCount++;
而且,由于您还没有使用for-each
-
char[] chars = in.toCharArray();
for (int i = 0; i < chars.length; i++) {
if (chars[i] == guess) {
count++;
}
}
答案 1 :(得分:-1)
每次完成响应以更新循环时,您都需要询问用户输入。
你的变量猜测从未在循环内更新,这就是它运行到无限循环的原因。你已经在循环中更新了猜测变量。