代码尚未完成,但我遇到了一些问题。这是我当前的代码:
public class Engine
{
public static void main(String[] args)
{
String word = JOptionPane.showInputDialog("Player 1! Please enter a word.");
JOptionPane.showMessageDialog(null, "Switch to Player 2. It is time to play hangman!");
char[] letters = word.toCharArray();
String[] underscores = new String[word.length()];
for(int i=0; i<=word.length()-1; i++)
{
underscores[i]="_ ";
}
StringBuilder builder = new StringBuilder();
for (int i=0; i<word.length(); i++)
{
builder.append(underscores[i]);
}
int mistakes = 0;
while(mistakes!=7)
{
String answer = JOptionPane.showInputDialog(null, "Please guess a letter.\n" + "Mistakes = " + mistakes + " of 7!\n\n" + builder.toString() + "\n\n");
char guess = answer.charAt(0);
for(int i=0; i<=word.length()-1; i++)
{
if(guess==letters[i])
{
underscores[i] = answer;
for (int x=0; x<word.length(); x++)
{
builder.append(underscores[x]);
}
}
}
}
}
}
我遇到的问题是 StringBuilder 部分和 .append()
例如,如果这个词是“帽子”。将出现一个带有三个下划线的窗口,如下所示:
如果我猜“h”,那么它会变成:
_ _ _ H _ _
代替
H _ _
此外,如果我接下来猜测“t”,它将变为:
_ _ _ h _ _ h _ t
它将数组的更改元素添加到已经存在的数组中。我很确定它是由 append 方法引起的,但我不知道任何替代方法。