在 GUI 中遍历一个数组 Java

traverse an array in GUI Java

我正在做一份包含问题和书面答案的问卷调查。 我需要在添加答案时,按下主按钮,告诉我答案是否正确,并显示数组的其他问题,直到数组完成。这里我上传整个代码。

mainbutton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
    for(int i=0;i<question;i++) {
        if(answer.getText()==(option[i])) {
        message.setText("is correct");
        corrects++;
                }
    else {
    message.setText("incorrect");
       }
  
};

你的想法是对的,但是你需要一次处理一个问题,而不是在 ActionListener 中一次处理所有问题。

解决这个问题的一种方法是在动作侦听器之外跟踪问题,在这个例子中我们使用 int questionCounter = 0; 来跟踪当前问题,然后我们可以删除 for 循环并一次处理一个问题。这是一个简单的示例,说明它如何使用您的代码工作,请注意我们如何重置字段并在每次回答上一个问题时添加下一个问题。

//Use a variable outside of the action listener to keep track of the current question:
int questionCounter = 0;

//Show first question in the text area:
area.setText(question[questionCounter]);

mainbutton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {

    if(answer.getText().equals(option[questionCounter])) {
        message.setText("The previous answer was correct");
        corrects++;
        //Update the total each time you get one correct
        correct_answers.setText("correct answers: "+corrects);
    }
    else {
        message.setText("The previous answer was incorrect");
    }
    
    //Increment for the next question    
    questionCounter++;

    //Check if there is another question, then show it
    if (questionCounter < question.length){
        answer.setText("");
        area.setText(question[questionCounter]);
    }
    //Show the overall results if there are no more answers to check
    else{
        area.setText("Quiz complete, you got " + corrects + " out of " + question.length + " correct.");
    }
};