2

I want to display 5 different comments when a button (Answer Btn) is clicked. Here we can see the JOption message dialog showing "Correct" comment. enter image description here

When I click the Answer button again, I want it to display another comment like "Great Job".

Here is the code for my ansBtnListener

class ansBtnListener implements ActionListener {
    public void actionPerformed(ActionEvent e) {
        // checking answer is correct or wrong
            double doubleOfInput = Double.parseDouble(input.getText()); // getting string to double
            if (doubleOfInput == result) {
                JOptionPane.showMessageDialog(null, "Correct");
            } else {
                JOptionPane.showMessageDialog(null, "Wrong, Try Again!");
                input.setText(" ");
            }

    }
}

Any help is much appreciated.

WiloWisk
  • 137
  • 3
  • 10

1 Answers1

1

You can add a method local variable and initially assign that to zero. So for the first time if the user is answering also check the value of that variable in if clause. If the value is 0 then show 'Correct' and increment the value by 1, and if the user is pressing the answer button again you will get that from the value of the variable and show 'Great Job' or 'Excellent' as required then.

class ansBtnListener implements ActionListener {
    int count = 0;
    public void actionPerformed(ActionEvent e) {
    // checking answer is correct or wrong
        double doubleOfInput = Double.parseDouble(input.getText()); // getting string to double
        if (doubleOfInput == result && count==0) {
            JOptionPane.showMessageDialog(null, "Correct");
            count++;
        }
        else if (doubleOfInput == result && count==1) {
            JOptionPane.showMessageDialog(null, "Great Job!");
            count++;
        }
        else if (doubleOfInput == result && count==2) {
            JOptionPane.showMessageDialog(null, "Excellent!");
            count++;
        }
        else if (doubleOfInput == result && count>2) {
            JOptionPane.showMessageDialog(null, "Please click on end!");
        }
        else {
            JOptionPane.showMessageDialog(null, "Wrong, Try Again!");
            input.setText(" ");
        }
    }
}
Rajesh Sinha
  • 47
  • 1
  • 8
  • Hi thank you for this, but is there a way to shuffle the messages being shown? For example if the first dialog box is "Correct", the second dialog box is "Great Job!", and the third dialog box is "Excellent", how can I shuffle or loop this so it will be shown randomly whenever the Answer button is clicked? – WiloWisk Jun 23 '20 at 06:05