秘密文字游戏

时间:2015-10-19 13:03:32

标签: java

我被指派创建一个猜谜游戏,你会在星号中给出一个秘密词,并有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变量中,只要在密码字中找到字母,那么该字母就会替换提示字中的星号。 以下是可能有用的说明列表。

  • 此类有三个实例变量
  • secretWord:用户这个词 必须猜测
  • 提示:带有猜测字母的单词
  • numberOfTurns:跟踪猜测次数
  • 此类仅需要默认构造函数
  • 您设置了密码
  • 转数为默认值0
  • 提示词是使用星号(*)为隐藏字中的每个字母构建的
  • 每个实例变量的访问者
  • 每个实例变量的Mutators CHECK FOR VALID VALUES!

1 个答案:

答案 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;
}
相关问题