所以我正在为这个全新的、从未听说过的游戏 hangman (ha.) 编写一个程序,而且我很难编写一个循环来给我想要的结果。我被困在一个正确的字母被猜到的地方(通过按钮按下)并在代表隐藏单词的破折号行中显示正确的字母。现在,当我运行这个循环时,我的测试器弹出窗口仍然会弹出“匹配!---”或者当前的秘密单词有多少破折号。从字面上看,就好像 replaceAll 实际上并没有替换它!我已经为此困扰了好几个小时,没有休息,所以如果我错过了一些非常明显的东西,我不会感到惊讶。
JButton btnA = new JButton("A\n");
btnA.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String letter = "a";
char ch = 'a';
if (go.getWordInQuestion().contains(letter)) {
for(int i = 0; i<go.getWordInQuestion().length(); i++) {
//Replace dashes with correctly guessed letter
if(go.getWordInQuestion().charAt(i)== 0)
go.getGuessLength().replaceAll("[^" + letter + "]", "_").charAt(i);
}
//check to see what the new value of the "hidden word" getGuessLength looks like
JOptionPane.showMessageDialog(null, "Match! " + go.getGuessLength());
txtGuess.setText("" + go.getGuessLength());
} else
JOptionPane.showMessageDialog(null,"No Match :(");
}
});
*****编辑******* 好的,所以我已经取得了进展(我认为)。我现在写了一个循环,将破折号更改为字母!!唯一的问题?它改变了所有这些。-___- 所以现在当我按下按钮 A 时,如果有匹配项,而不是 ---,它将读取 aaa。我绝对意识到这个问题可能非常初级,但是当涉及到 java 时,我是一个学习缓慢的人!我感谢所有积极和信息丰富的反馈!
JButton btnA = new JButton("A\n");
btnA.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String letter = "a";
StringBuilder guessA = new StringBuilder('a');
for(int i = 0; i<go.getGuessLength().length();i++) {
if(go.getWordInQuestion().charAt(i)=='a') {
String partialWord = go.getGuessLength().replace("-", letter);
txtGuess.setText(partialWord);
JOptionPane.showMessageDialog(null,"Match! " + partialWord);
}
}
}
});
*****编辑两个******
好吧!我想我终于解决了这个问题,感谢你们的帮助!当用户按下“A”按钮时,如果隐藏单词中有 A,现在它已成功替换为破折号!呜呼!
btnA.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String letter = "a";
StringBuilder guessA = new StringBuilder(go.getGuessLength());
if(go.getWordInQuestion().contains(letter)) {
for(int i = 0; i<go.getGuessLength().length();i++) {
if(go.getWordInQuestion().charAt(i)=='a') {
StringBuilder partialWord = guessA.replace(i,i+1, letter);
txtGuess.setText(guessA.toString());
JOptionPane.showMessageDialog(null,"Match! " + partialWord);
}
}
} else
JOptionPane.showMessageDialog(null, "Incorrect");
}
});