嗨,我是编程新手,我们的任务是创建一个刽子手游戏。现在我遇到的问题是猜测。该程序猜测一切正确,并且工作正常。虽然它不会打印出 中的字母JTextField
,或者它确实打印出 1 个字母,但是当我再次猜对时,前一个字母会被覆盖。
那么有没有友好的灵魂可以伸出援助之手?
这是我的检查代码:
private class check implements ActionListener {
public void actionPerformed(ActionEvent ae) {
try {
// Grabs the letter from the guessField and converts it into a char which can be used to compare against the word.
guess = guessField.getText();
guessField.setText("");
char guess2 = guess.charAt(0);
String displaySecret = "";
for (int i = 0; i < random.length(); i++)
displaySecret += "*";
//read in a guess
int position = random.indexOf(guess2);
//now position contains the index of guess inside secret, or
//-1 if the guess was wrong
String newDisplaySecret = "";
for (int i = 0; i < random.length(); i++)
if (i == position)
newDisplaySecret += random.charAt(i); //newly guessed character
else
newDisplaySecret += displaySecret.charAt(i); //old state
displaySecret = new String(newDisplaySecret);
wordField.setText(displaySecret);
}