嘿傢伙我在這裏有一個程序,其中用戶需要猜測程序本身要求的單詞。這些代碼沒有語法錯誤,但我的問題在於,每次輸入正在請求的正確單詞時,JOptionPane(ErrorMessage)仍然出現。雖然while循環錯誤
我想要發生的是,用戶只能進行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));
}
我們可以看到isCorrect的代碼嗎?它可能總是返回錯誤。 –
我會把5美元比作字符串而不是equals()! –
...或equalsIgnoreCase()... – vefthym