我正在尝试在java中创建一个GUI,我有两个JTextfields。一个文本字段显示问题,该问题是表单的哈希映射(问题:答案),其中问题存储为键并作为值回答。问题显示在一个名为aTextField的文本字段中,用户在answerField中输入答案。现在我想检查用户是否提供了正确的答案。这是我的代码:
guessAA.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
String answerFieldValue =answerField.getText().toUpperCase();
int idx = indexGenerator.nextInt(19);
String key = FULL_NAMES[idx];
aTextField.setText("Guess this " + key);
if(answerFieldValue != null && !answerFieldValue.isEmpty())
{
System.out.println("your input " + answerFieldValue);
System.out.println("correct answer " + myMap.get(key));
}
现在输出的是: 你的输入C. 正确答案T. 你的输入T. 正确答案W 你的输入W. 正确答案G
因此,您可以看到我的问题始终存储为下一个,所以我永远无法进行比较。有人可以帮忙吗?感谢
答案 0 :(得分:0)
我认为你正在寻找以下内容:
if(myMap.get(key).equals(answerFieldValue)){
//answer was right
}else{
//answer was wrong
}
答案 1 :(得分:0)
对我而言,“看起来”似乎是在确认当前问题之前你正在转向下一个问题,所以你似乎在看下一个问题的答案而不是当前问题的答案。
这表明你需要什么,是对当前问题的某种参考。
现在,因为我无法访问您的整体代码,所以我所能做的就是提供您可以做的概念概述......
public class YourAwesomeGuessingGame extends ... {
private String currentQuestionKey;
public YourAwesomeGuessingGame() {
// Seed the current question key with the first question
currentQuestionKey = ...;
// Update the UI
guessAA.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
String correctAnswer = myMap.get(key));
String answerGiven = answerField.getText().toUpperCase();
// Compare the results, take appropriate action
// Seed the current question key with the next question
currentQuestionKey = ...;
// Update the UI
}
}
}
}