Compare users input

80 views Asked by At

I have a text.file with questions and another text.file with the correct answers to the questions. My program contains some JButton-s and when the user clicks on the button it shows a new pane with a question with multiple choice answers, then the user is asked to write the letter of the correct answer. I have done this things and it works. But I want to compare the entered answer with correct answer and store only the number of correct answers in a text.file
If you can give some advice or an example code i will really appreciate it. Thank you in advance and here is my code, where I need to add this things.

  JTextField xField = new JTextField(5);

                JPanel myPanel = new JPanel();
                myPanel.add(new JLabel("Answer: "));
                myPanel.add(xField);
                myPanel.add(Box.createHorizontalStrut(20));

                int result = JOptionPane.showConfirmDialog(null, myPanel,
                        "Please Enter your Answer", JOptionPane.OK_CANCEL_OPTION);

                return;
            }

        }

    }
2

There are 2 answers

0
Uma Kanth On

What I suggest you to do is to read the file of the questions and populate it in a JLabel, and then take it's respective answer.

We instead of having a textBox you could have radioButtons, If there is only a single answer.

In case you have multiple options, you can use checkBoxes.

How to create a Label

JLabel questionLabel = new JLabel(question);

How to create a radioButton.

JRadioButton optionA = new JRadioButton("A. "+ option[ 0 ]);
JRadioButton optionB = new JRadioButton("B. "+ option[ 1 ]);
JRadioButton optionC = new JRadioButton("C. "+ option[ 2 ]);
JRadioButton optionD = new JRadioButton("D. "+ option[ 3 ]);

ButtonGroup group = new ButtonGroup();
group.add(optionA);
group.add(optionB);
group.add(optionC);
group.add(optionD);

Now loop through your radioButtons, and get your option and check with the actual answer.

1
Jef Vrijhoeven On

I have made a similar application some years ago. What I did was putting the questions with some answers in a text file. The first answer was always the correct answer. When a question was shown on the screen (with its possible answers), I used a method to change the order of the possible answers, and remembered the number (or letter) of the correct answer. Then, when I received the input from the user, it was easy to compare the answer to the correct answer.

In my application, I did not ask to input a letter, but I used radio buttons, from which the user had to select 1. The advantage of input from the key board, is that a user might use upper/lower case, or ad a white space, or so, which makes that the correct answer might not be recognized. Radio buttons are much easier to compare, as you will receive teh number of the selected button, without possible unexpected extra input from the user.