我的任务是创建一个猜词游戏。您只有 5 次尝试猜测该单词的机会。用户一次输入一个字母,试图找出我的秘密单词“果汁”,但您应该使用提示单词构造,每次猜测都会用正确的字母替换星号(如果正确)。
输出应该是这样的:
欢迎来到猜词游戏!您有 5 次机会尝试猜出这个秘密单词!
目前的提示是
猜一个小写字母
u
*u***
猜猜秘密词
tutre
继续尝试!
猜一个小写字母
t
*u***
猜猜秘密词
mutor
继续尝试!
...继续直到 5 次尝试,然后你要么赢要么输
我的输出不会一直让您尝试猜测,而且提示词显然很混乱,因为它的 5 个星号前面有空。我不知道如何修复它。
目前的提示是
无效的*****
猜一个小写字母
j
jull*
猜猜秘密词
jutre
继续尝试!
游戏结束!再试一次?
这是我的班级:
public class SecretWord {
private String secretWord;
private String hintWord;
private int numberOfTurns;
//Default Constructors
public SecretWord()
{
this.secretWord = "juice";
for (int i = 0; i < secretWord.length(); i++)
{
this.hintWord+="*";
}
this.numberOfTurns = 0;
}
//Accessors
public String getSecretWord()
{
return this.secretWord;
}
public String getHintWord()
{
return this.hintWord;
}
public int getNumberOfTurns()
{
return this.numberOfTurns;
}
//Mutators
public void setSecretWord ()
{
this.secretWord = "juice";
}
public void setHintWord ()
{
char[] correctLetters = new char[secretWord.length()];
for (int i = 0; i<secretWord.length();i++)
{
hintWord+="*";
correctLetters[i] += '*';
}
}
public void setNumberOfTurns (int i)
{
this.numberOfTurns = 5;
}
//Methods
public void guessLetter(char guess)
{
String tempHintWord="";
for (int i = 0; i < secretWord.length(); i++)
{
if (secretWord.charAt(i) == guess)
{
tempHintWord += guess;
}
else
{
tempHintWord += hintWord.charAt(i);
}
}
hintWord = tempHintWord;
}
这是我的驱动程序类:
public class SecretWordGame {
//Constant for number of tries
public static final int NUM_TRIES = 5;
public static void main (String[] args)
{
Scanner keyboard = new Scanner(System.in);
//Starts game
boolean quit = false;
while (quit == false)
{
System.out.println("Welcome to the word guessing game! You have " +
+NUM_TRIES+" tries to guess the secret word!");
SecretWord myWord = new SecretWord();
System.out.println("The current hint is \n"+myWord.getHintWord());
while (myWord.getNumberOfTurns() <NUM_TRIES)
{
System.out.println("Guess a lowercase letter");
//Gets the first letter of what is entered
char guess = keyboard.nextLine().charAt(0);
//Updates the hint by calling guess letter method
myWord.guessLetter(guess);
System.out.println(myWord.getHintWord());
System.out.println("Guess the secret word");
String myGuess = keyboard.nextLine();
//Checks correct guess
if (myGuess.equals(myWord.getSecretWord()))
{
System.out.println("You win!");
break;
}
else
{
System.out.println("Keep trying!");
}
myWord.setNumberOfTurns(myWord.getNumberOfTurns()+1);
}
//Prompts user to play again
System.out.println("Game over! Try again?");
String userInput = keyboard.nextLine();
if(userInput.equalsIgnoreCase("no"))
{
quit = true;
}
else
{
System.out.println("Let's go again!");
}
}
System.out.println("Goodbye!");
}
SecretWord
's hintword
被初始化为null
默认情况下。所以当你附加它时+= "*"
它将当前值转换为"null"
然后添加"*"
。如果您在声明它的地方初始化hinword""
它将解决这个问题。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)