1 回答
TA贡献1887条经验 获得超5个赞
创建单词和空白全局变量以及在调用构造函数时设置变量的构造函数。像下面。
将创建空白字符数组的行printWord()移到构造函数中。因为每次调用时printWord都会创建一个新的空白数组或替换旧数组,这就是为什么打印空白是不正确的。您只想设置一次空白字符数组,构造Hangman()将是最好的地方,因为在创建 Hangman 对象 ( Hangman hangman = new Hangman();)时只调用一次。我希望这是有道理的。
让我知道这是否解决了您的问题。
添加/更新代码
public class Hangman {
private String word;
private char[] blank;
private int guesses;
public Hangman() {
word = "Toyota";
blank = new char [word.length()];
for (int i =0; i < word.length(); i++){
blank[i] = '*';
}
guesses = 0;
}
// Optional Constructor - Hangman hangman = new Hangman("Toyota");
public Hangman(String word) {
this.word = word;
blank = new char [word.length()];
for (int i =0; i < word.length(); i++){
blank[i] = '*';
}
guesses = 0;
}
/**
* Rest of your code
*/
}
删除代码- 删除从printWord()方法中标记的注释行
//String word = "Toyota";
int count = 0;
//char [] blank = new char [word.length()];
//for (int i =0; i < word.length(); i++){
// blank[i] = '*';
//}
更新 - 更改 printStatus
public static void printStatus(char c){
String mystring = "abcdefghijklmnopqrstuvwxyz";
int count = 0;
StringBuilder sb = new StringBuilder();
sb.append(mystring);
for (int i = 0; i < sb.length(); i++){
if (c ==sb.charAt(i)){
sb.deleteCharAt(i);
}
}
guesses++;
System.out.println(sb.toString());
System.out.println("The number of guesses are: " + guesses);
}
添加回答
举报