繁体   English   中英

在 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.");
    }
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM