【发布时间】:2014-12-24 09:18:50
【问题描述】:
现在在课堂上,我们被分配了另一个使用数组的 Hangman 项目,我们必须生成“_”。 当用户输入“wordAnswer”时,我已成功生成所有空格。 我的问题是我不知道如何用空白“_”替换正确的猜测字符。
这是我的整个程序的代码,我知道它并不完整。
import cs1.Keyboard;
public class Game {
public static void main(String[] args) {
int correctGuess = 0;
int wrongGuess = 0;
int bodyParts = 0;
char guess;
boolean foundIt;
System.out.println("Welcome to Hangman!");
System.out.println("Please enter a word for the other user to guess!");
String wordAnswer = Keyboard.readString();
char[] chars = wordAnswer.toCharArray();
char[] blanks = new char[wordAnswer.length()];
System.out.println("You have 6 attempts to guess the word!");
do {
for (int i = 0; i < wordAnswer.length(); i++) {
System.out.print(" _ ");
}
System.out.println("Please enter in your guess!");
guess = Keyboard.readChar();
for (int i = 0; i < chars.length; i++) {
if (guess == chars[i]) {
blanks[i] = guess;
foundIt = true;
}
}
} while (correctGuess < wordAnswer.length() && wrongGuess != 6); {
System.out.println("Congratulations! You have solved the word!");
}
}
}
我知道您必须使用 for 循环才能将空格更改为正确猜测的字母,但是当您运行程序并输入正确的猜测时,空格不会更改为正确的字母。 这是我的输出
Welcome to Hangman!
Please enter a word for the other user to guess!
program
You have 6 attempts to guess the word!
_ _ _ _ _ _ _ Please enter in your guess!
p
_ _ _ _ _ _ _ Please enter in your guess!
r
_ _ _ _ _ _ _ Please enter in your guess!
o
_ _ _ _ _ _ _ Please enter in your guess!
g
_ _ _ _ _ _ _ Please enter in your guess!
r
_ _ _ _ _ _ _ Please enter in your guess!
a
_ _ _ _ _ _ _ Please enter in your guess!
m
_ _ _ _ _ _ _ Please enter in your guess!
我期待的是!!
Welcome to Hangman!
Please enter a word for the other user to guess!
program
You have 6 attempts to guess the word!
_ _ _ _ _ _ _ Please enter in your guess!
p
p _ _ _ _ _ _ Please enter in your guess!
r
p r _ _ _ _ _ Please enter in your guess!
o
p r o _ _ _ _ Please enter in your guess!
等等……
这是我所拥有的,但非常感谢提示和帮助!
System.out.println("Please enter in your guess!");
guess = Keyboard.readChar();
for (int i = 0; i < chars.length; i++) {
if (guess == chars[i]) {
blanks[i] = guess;
foundIt = true;
}
}
【问题讨论】:
-
“不工作”不是一个有用的问题描述。 如何“不工作”?编译错误?运行时异常?什么是错误/异常?你谷歌它是为了努力了解它是什么以及它为什么会发生吗?还是不正确的行为?发生了什么?你期望会发生什么?更详细。
-
还是不太清楚。您是否希望在第二行看到
p _ _ _ _ _ _ _ _,在第三行看到p r _ _ _ _ _,等等? -
好的,我已经更新了它,我认为我真的不能更具体。我正在寻找的是正确猜测的字母来替换“_”空白。
-
您只需要最初用
_填充blanks数组并始终打印其成员,而不是硬编码的下划线。
标签: java arrays loops for-loop