嘿伙计我在这里有一个程序,其中用户需要猜出程序本身正在询问的单词。代码没有语法错误,但我的问题是,每次输入正在要求的正确单词时,JOptionPane(ErrorMessage)仍会出现。
我想要发生的是,用户只能进行5次试验,一旦用户在最后一次试验中输入错误的单词,它应该显示要求的正确单词。一旦用户输入了正确的单词,它就应该转到下一个单词。请帮我解决这个问题我已经在这里呆了3个小时了。非常感谢你。
private void guessedWordActionPerformed(java.awt.event.ActionEvent evt) {
int trials = 5;
boolean tryAgain = true;
do{
if (wordLibrary.isCorrect(wordIdx, guessedWord.getText())){
JOptionPane.showMessageDialog(null, "Your answer is correct! Guess another word.","", JOptionPane.INFORMATION_MESSAGE);
getRootPane().setDefaultButton(nextTrial);
guessedWord.setText("");
wordIdx = (wordIdx + 1) % wordLibrary.getSize();
scrambledWord.setText(wordLibrary.getScrambledWord(wordIdx));
guessedWord.setText("");
getRootPane().setDefaultButton(guessButton);
guessedWord.requestFocusInWindow();
tryAgain = false;
}
else if (!wordLibrary.isCorrect(wordIdx, guessedWord.getText())) {
JOptionPane.showMessageDialog(null, "Your answer " + guessedWord.getText() + " is wrong.\n Number of trials remaining: " + trials ,
"Incorrect Answer", JOptionPane.ERROR_MESSAGE);
trials--;
guessedWord.setText("");
tryAgain = true;
}
}while(tryAgain && trials > 0);
guessedWord.requestFocusInWindow();
}
//This is the isCorrect method
public boolean isCorrect(int idx, String userGuess) {
return userGuess.equalsIgnoreCase(getWord(idx));
}
答案 0 :(得分:2)
这是在您执行的操作中发生的。循环时,您不会给用户任何时间输入新信息。
你为什么要在这里循环?你不需要它。只需检查一次。如果他们错了,请更改组件并等待再次调用ActionPerformed
。
如果您想提供最大数量的试验,那么您应该使用某种形式的非本地变量来存储它。
答案 1 :(得分:1)
当你第一次给出错误的答案时,guessedWord的文本变成空字符串“”,所以在下一次迭代中,它永远不会等于给定的单词,因为你用guessedWord.getText()
得到的字符串现在是“”。
您需要询问用户一个新单词,然后获取新单词!
例如,您可以在类中设置一个私有变量int trials
,初始化为5(在您的main方法中),另一个,boolean tryAgain
初始化为true。然后上面的方法可以写成:
private void guessedWordActionPerformed(java.awt.event.ActionEvent evt){
if (tryAgain && trials > 0) {
if (wordLibrary.isCorrect(wordIdx, guessedWord.getText())){
JOptionPane.showMessageDialog(null, "Your answer is correct! Guess another word.","", JOptionPane.INFORMATION_MESSAGE);
getRootPane().setDefaultButton(nextTrial);
guessedWord.setText("");
wordIdx = (wordIdx + 1) % wordLibrary.getSize();
scrambledWord.setText(wordLibrary.getScrambledWord(wordIdx));
guessedWord.setText("");
getRootPane().setDefaultButton(guessButton);
guessedWord.requestFocusInWindow();
tryAgain = false;
} else {
trials--;
JOptionPane.showMessageDialog(null, "Your answer " + guessedWord.getText() + " is wrong.\n Number of trials remaining: " + trials ,
"Incorrect Answer", JOptionPane.ERROR_MESSAGE);
guessedWord.setText("");
tryAgain = true;
}
} else {
//show "the correct word was..."
}
guessedWord.requestFocusInWindow();
}