我让自己成为一个Hangman游戏,基本上我遇到的唯一问题是,每次我猜一封新信时,这些字母都会加倍。例如,如果单词是" Hello World"我猜到了#34; l"它会打印出来 " _ _ l l _ _ _ _ l _",对,然后如果我猜" w"接下来,它打印" H _ _ _ l _ l _ _ _ _ _ _ _ _ _ l _ _ _" (这是hheelllloo wwoorrlldd)。
我的代码如下所示。我的想法是,因为我有一个嵌套的for
循环,但我不知道我还能做些什么。
// This checks previous letters given through String guessedlet.
for(int spot = 0; spot < wrd[0].length(); spot++)
{
for (int spot2 = 0; spot2 <= guessedlet.length() - 1; spot2++)
{
char Spot = wrd[0].charAt(spot);
String wordletter = Character.toString(Spot);
char Spot2 = guessedlet.charAt(spot2);
String guessedletter = Character.toString(Spot2);
for(int spot3 = 0; spot3 < guessedlet.length(); spot3++)
{
char Spot3 = guessedlet.charAt(spot3);
String guessedletter2 = Character.toString(Spot3);
if(letter.equals(guessedletter2))
{
break;
}
}
if(guessedletter.equals(wordletter))
{
wordletter = guessedletter;
}
else if(guessedletter.equals(" "))
{
wordletter = "";
}
else if(!(guessedletter.equals(wordletter)))
{
wordletter = "_";
}
out.print(wordletter + " ");
}
}
为什么这些字母是重复的?
答案 0 :(得分:0)
您需要将输出移出内部循环,如下所示:
for(int spot = 0; spot < wrd[0].length(); spot++)
{
String tempDisplay = "_";
for (int spot2 = 0; spot2 <= guessedlet.length() - 1; spot2++)
{
char Spot = wrd[0].charAt(spot);
String wordletter = Character.toString(Spot);
char Spot2 = guessedlet.charAt(spot2);
String guessedletter = Character.toString(Spot2);
for(int spot3 = 0; spot3 < guessedlet.length(); spot3++)
{
char Spot3 = guessedlet.charAt(spot3);
String guessedletter2 = Character.toString(Spot3);
if(letter.equals(guessedletter2))
{
break;
}
}
if(guessedletter.equalsIgnoreCase(wordletter))
{
tempDisplay = guessedletter;
break;
}
}
out.print(tempDisplay + " ");
}
您只想为wrd[0]
...