我被指派创建一个猜谜游戏,你会在星号中给出一个秘密词,并有5次尝试猜测正确的单词。他们一次输入一封信,这些字母在单词中显示出来。与刽子手不同,每个回合都很重要,而不仅仅是每次他们选择一个不在单词中的字母。该类只需要一个默认构造函数这是我到目前为止的代码,这里是驱动程序:http://pastebin.com/35T9B4wM
public class SecretWord {
private String secretWord;
private String hintWord;
private int numberOfTurns;
public SecretWord()
{
this.secretWord = "fruit";
this.numberOfTurns = 0;
for(int i=0;i<secretWord.length();i++)
{
hintWord+="*";
}
}
public String getSecretWord()
{
return this.secretWord;
}
public String getHintWord()
{
return this.hintWord;
}
public int getNumberOfTurns()
{
return this.numberOfTurns;
}
public void setSecretWord()
{
this.secretWord = "fruit";
}
public void setHintWord()
{
}
public void setNumberOfTurns(int i)
{
this.numberOfTurns = 5;
}
public void guessLetter()
{
}
}
我只是不明白访问者或变异者应该做些什么。或者在guessLetter变量中,只要在密码字中找到字母,那么该字母就会替换提示字中的星号。 以下是可能有用的说明列表。
答案 0 :(得分:0)
hintWord
之后。这样的事情应该可以解决问题。
hintWord = "";
for (int i = 0; i < secretWord.length(); i++){
if (secretWord.charAt(i) == guess){ //Check if we found anything
//found = true; We do not need this variable since we already know if we found something
correctLetters[i] = guess;
}
hintWord += correctLetters[i];
}
只需确保您的correctLetters
在开头设置正确。您可以在setHintWord
中进行设置。像这样:
public void setHintWord(){
correctLetters = new char[secretWord.length()];
for(int i=0;i<secretWord.length();i++)
{
hintWord+="*";
correctLetters[i] += '*';
}
}
如果您不想跟踪另一个实例变量(因为您的说明只说使用3),您可以使用临时String
执行此类操作。
public void guessLetter(char guess){
String tempHintWord = "";
for (int i = 0; i < secretWord.length(); i++){
if (secretWord.charAt(i) == guess){ //Check if we found anything
//found = true; We do not need this variable since we already know if we found something
tempHintWord += guess;
}else{
tempHintWord += hintWord.charAt(i);
}
}
hintWord = tempHintWord;
}