Skip to content
Advertisement

traverse an array in GUI Java

I am doing a questionnaire with questions and written answers. I need that when adding the answer, press the main button, tell me if it is correct or not and show me the other question of the array, until the array is finished. Here I upload the whole code.

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

Advertisement

Answer

You have the right idea, but you need to process the questions one at a time, not all at once inside the ActionListener.

One way to approach this is to keep track of the question outside of the action listener, in this example we use int questionCounter = 0; to keep track of the current question, then we can remove the for loop and process the questions one at a time. Here is a simple example of how it could work using your code, note how we reset the fields and add the next question every time the previous question is answered.

//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.");
    }
};
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement