Question

I am making a math practice application. It is to loop 10 random questions and have counters that show how many you have got right and how many you have got wrong.

I tried to do some exception handling so that when no value is entered a pop up comes up. When the pop up comes up the counter for the wrong answer counter or the right answer counter is incremented no matter what.

here is the code:

import javax.swing.*;

import java.awt.*;
import java.awt.event.*;



@SuppressWarnings("serial")
public class MathPractice extends JFrame {
    Container c;
    JPanel output;
    JLabel title, num1, num2, lbloperator, equals, mark, display, correct, wrong ,correctN, wrongN;
    JTextField answer;
    JButton newB, ansB;
    JTextArea txtdisplay;

    String operator;

    int number1;int number2;int rightNum = 0;int wrongNum = 0;int result;int random;int randomOperator; int cnt = 1;

    public int getRandom(){
        int random = (int)(Math.random() * 10 + 1);
        return random;
    }
    public String getRandomOperator(){
        int randomOperator = (int)(Math.random() * 4 + 1);
        if(randomOperator == 1)
            return "+";
        else if (randomOperator == 2)
            return "-";
        else if (randomOperator == 3)
            return "*";
        else {
            return "/";
        }       
    }

    class ExcerciseHandler implements ActionListener {
        public void actionPerformed(ActionEvent e) {
                number1 = getRandom();
                number2 = getRandom();

                num1.setText(""+number1);
                num2.setText(""+number2);

                operator = getRandomOperator();

                lbloperator.setText(operator);

                rightNum = 0;
                wrongNum = 0;
                cnt = 1;

                correctN.setText("" + rightNum);
                wrongN.setText("" + wrongNum);
                display.setText("");

                answer.setText("");
            }
        }



    class AnswerHandler implements ActionListener {
        public void actionPerformed(ActionEvent e) {            
                    boolean canRun = true;
                    double input = 0;
                    try{
                    input = Double.parseDouble(answer.getText());               
                    }
                    catch (Exception ex){
                        canRun = false;
                        JOptionPane.showMessageDialog(null, "Please enter a valid number!");
                        answer.requestFocus();
                        answer.selectAll();
                    }
                    operator = lbloperator.getText();   

                if(cnt <= 10){
                    if (operator.equals("+")){
                        result = number1 + number2;
                        if(input == result){
                            rightNum++;
                            correctN.setText(""+rightNum);
                        }
                        else {
                            wrongNum++;
                            wrongN.setText(""+wrongNum);
                        }
                    }
                    else if (operator.equals("-")){
                        result = number1 - number2;
                        if(input == result){
                            rightNum++;
                            correctN.setText(""+rightNum);
                        }
                        else {
                            wrongNum++;
                            wrongN.setText(""+wrongNum);
                        }

                    }
                    else if (operator.equals("*")){
                        result = number1 * number2;
                        if(input == result){
                            rightNum++;
                            correctN.setText(""+rightNum);
                        }
                        else {
                            wrongNum++;
                            wrongN.setText(""+wrongNum);
                        }
                    }
                    else {
                        result = number1 / number2;
                        if(input == result){
                            rightNum++;
                            correctN.setText(""+rightNum);
                        }
                        else {
                            wrongNum++;
                            wrongN.setText(""+wrongNum);
                        }                   
                    }
                    number1 = getRandom();
                    number2 = getRandom();

                    num1.setText(""+number1);
                    num2.setText(""+number2);

                    lbloperator.setText("" + getRandomOperator());

                    answer.setText("");
                    answer.requestFocus();

                    cnt++;  


                }
                if (cnt == 11 && rightNum > 6){
                    display.setText("Keep up the good work!");
                }
                else if (cnt == 11 && rightNum <= 6){
                    display.setText("Better luck next time!");
                }
            }
    }



    Font f = new Font("Arial", Font.BOLD, 20);
    Font numbers = new Font("Arial", Font.PLAIN, 30);
    Font operators = new Font("Arial", Font.PLAIN, 20);
    Font outputF = new Font("Arial", Font.ITALIC, 15);
    Font fAnswers = new Font("Arial", Font.BOLD, 30);



    MathPractice (){
        super("Math Practice");
        c = getContentPane();
        c.setLayout(null);
        //c.setBackground(Color.blue);

        title = new JLabel("How Much is: ");
        title.setSize(150,20);
        title.setLocation(130, 5);
        title.setFont(f);
        title.setForeground(Color.red);

        number1 = getRandom();
        num1 = new JLabel(""+ number1);
        num1.setSize(40, 40);
        num1.setLocation(30, 35);
        num1.setFont(numbers);

        lbloperator = new JLabel(getRandomOperator());
        lbloperator.setSize(40, 40);
        lbloperator.setLocation(85, 37);
        lbloperator.setFont(operators);

        number2 = getRandom();
        num2 = new JLabel(""+ number2);
        num2.setSize(40, 40);
        num2.setLocation(140, 35);
        num2.setFont(numbers);      

        equals = new JLabel(" = ");
        equals.setSize(40, 40);
        equals.setLocation(200, 35);
        equals.setFont(numbers);

        answer = new JTextField(8);
        answer.setSize(80, 40);
        answer.setLocation(250, 35);
        answer.setFont(numbers);        

        mark = new JLabel("?");
        mark.setSize(40, 40);
        mark.setLocation(350, 35);
        mark.setFont(numbers);

        display = new JLabel("");
        display.setSize(350, 40);
        display.setLocation(30, 90);
        display.setFont(numbers);
        //display.setVisible(false);



        newB = new JButton("    New Excercise    ");
        newB.setSize(170, 40);
        newB.setLocation(15, 170);
        ExcerciseHandler eh = new ExcerciseHandler();
        newB.addActionListener(eh);

        ansB = new JButton("    Answer    ");
        ansB.setSize(170, 40);
        ansB.setLocation(195,170);
        AnswerHandler ah = new AnswerHandler();
        ansB.addActionListener(ah);

        output = new JPanel();
        output.setLayout(null);
        output.setSize(375, 225);
        output.setBorder(BorderFactory.createTitledBorder("Statistic: "));
        output.setLocation(5, 225);

        correct = new JLabel("<html> Number of Correct\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Answers: " );
        correct.setSize(150, 50);
        correct.setLocation(15, 25);
        correct.setFont(outputF);

        wrong = new JLabel("<html> Number of Wrong\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Answers: ");
        wrong.setSize(150, 50);
        wrong.setLocation(230, 25);
        wrong.setFont(outputF);

        correctN = new JLabel("" + rightNum);
        correctN.setSize(100, 100);
        correctN.setLocation(60, 50);
        correctN.setFont(fAnswers);
        correctN.setForeground(Color.green);

        wrongN = new JLabel("" + wrongNum);
        wrongN.setSize(100, 100);
        wrongN.setLocation(275, 50);
        wrongN.setFont(fAnswers);
        wrongN.setForeground(Color.red);    

        c.add(title);c.add(num1);c.add(lbloperator);c.add(num2);c.add(equals);c.add(answer);c.add(mark);c.add(display);c.add(newB);
        c.add(ansB);c.add(output);

        output.add(correct);output.add(wrong);output.add(correctN);output.add(wrongN);  
    }

    public static void main(String[] args) {
        MathPractice app = new MathPractice();
        app.setSize(400, 500);
        app.setVisible(true);
        app.setDefaultCloseOperation(DISPOSE_ON_CLOSE);

    }

}
Was it helpful?

Solution

Put a return; statement at the bottom of your catch block. This will cause your code to leave the handler after handling the exception when an exception occurs.

try{
   input = Double.parseDouble(answer.getText());               
}
catch (NumberFormatException ex){
   canRun = false;
   JOptionPane.showMessageDialog(null, "Please enter a valid number!");
   answer.requestFocus();
   answer.selectAll();

   return; // ****** added *****
}

As an aside: you should avoid catching Exception but instead should only catch specific Exceptions, here NumberFormatException.

OTHER TIPS

After showing the error popup, the method continues executing and therefore increasing the counter. End the method if a wrong value is entered, or loop until a correct value is entered.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top