【问题标题】:How do I count the correctly selected JRadioButton and Print a total "Score"?如何计算正确选择的 JRadioButton 并打印总“分数”?
【发布时间】:2016-03-31 07:05:38
【问题描述】:

我的申请是多项选择测验。现在只有两个问题,所以我可以测试逻辑,但是在我弄清楚它之后加起来是 100。真的我有一个新的框架,按钮添加到面板,然后面板添加到 JFrame。然后,我使用 nextQuestion() 方法允许我通过多个问题,只要还有问题。还有一个计时器,我通过他们的计时器,为每个问题提供时间,10 秒。

        protected void nextQuestion() {
            timer.stop();
            currentQuestion++;
            if (currentQuestion >= quiz.size()) {
                cardLayout.show(QuestionsPanel, "last");
                next.setEnabled(false);
                //Show however many correct after last question. 
                //iterate on the collection to count the selected radio buttons
                //What im confused about is really how do i tell the program which (options) are right or wrong. 
                //and if i can do that how do i only count the correct ones. 
                //or for example do i have to take the total questions and subtract by the ones they didnt choose? 
                //a code example on how to do this would be great. 
            } else {
                cardLayout.show(QuestionsPanel, Integer.toString(currentQuestion));
                startTime = null;
                next.setText("Next");
                next.setEnabled(true);
                timer.start();
            }
        }



    public interface Question {

        public String getPrompt();

        public String getCorrectAnswer();

        public String[] getOptions();

        public String getUserResponse();

        public void setUserResponse(String response);

        public boolean isCorrect();
    }

    public class ChoiceQuestion implements Question {

        private final String prompt;
        private final String correctAnswer;
        private final String[] options;

        private String userResponse;

        public ChoiceQuestion(String prompt, String correctAnswer, String... options) {
            this.prompt = prompt;
            this.correctAnswer = correctAnswer;
            this.options = options;
        }

        @Override
        public String getPrompt() {
            return prompt;
        }

        @Override
        public String getCorrectAnswer() {
            return correctAnswer;
        }

        @Override
        public String[] getOptions() {
            return options;
        }

        @Override
        public String getUserResponse() {
            return userResponse;
        }

        @Override
        public void setUserResponse(String response) {
            userResponse = response;
        }

        @Override
        public boolean isCorrect() {
            return getCorrectAnswer().equals(getUserResponse());
        }
    }

    public class QuestionPane extends JPanel {

        private Question question;

        public QuestionPane(Question question) {
            this.question = question;

            setLayout(new BorderLayout());

            JLabel prompt = new JLabel("<html><b>" + question.getPrompt() + "</b></html>");
            prompt.setHorizontalAlignment(JLabel.LEFT);

            add(prompt, BorderLayout.NORTH);

            JPanel guesses = new JPanel(new GridBagLayout());
            guesses.setBorder(new EmptyBorder(10,10,10,10));
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.gridwidth = GridBagConstraints.REMAINDER;
            gbc.weightx = 1;
            gbc.anchor = GridBagConstraints.WEST;

            List<String> options = new ArrayList<>(Arrays.asList(question.getOptions()));
            options.add(question.getCorrectAnswer());
            Collections.sort(options);

            ButtonGroup bg = new ButtonGroup();
            for (String option : options) {
                JRadioButton btn = new JRadioButton(option);
                bg.add(btn);

                guesses.add(btn, gbc);
            }

            add(guesses);

        }

        public Question getQuestion() {
            return question;
        }

        public class ActionHandler implements ActionListener {

            @Override
            public void actionPerformed(ActionEvent e) {
                getQuestion().setUserResponse(e.getActionCommand());
            }

        }

    }

}

所以我真的只是在做那个小的 if else 代码块时遇到了问题。如果你们能帮帮我。我有一些关于迭代集合的想法,尽管我不知道该怎么做。这些只是我使用的类和我遇到问题的方法。

【问题讨论】:

  • 您可以为CardLayout 使用一个简单的命名约定(即q1q2 等),并简单地保留一个指向当前问题的简单指针。我会更容易确定你是在测验的开始、结束还是中间的某个地方
  • 这在QuizPanel 中从same question 中得到了演示,您从...cardLayout.show(panelOfQuestions, Integer.toString(currentQuestion));...中获得了基本代码结构...
  • 好吧,抱歉。是的,我使用了我只是想知道的基本代码结构,因为过去两个小时我一直在尝试使这个测验起作用,你是怎么做的?它是循环单选按钮并使用 is.selected() 还是使用收集器?
  • @MadProgrammer 保留指向程序的指针会做什么。您不想拥有它,因此它会检查单击了哪些按钮,将其与正确答案进行比较并打印分数。我不确定我在这个逻辑上很糟糕。任何帮助都会很棒。
  • 并非如此,您可以使用currentQuestion 值在当前点向Quiz 询问Question 并检查它的isCorrect 值,然后再转到下一个Question。所以在nextQuestion方法中,你可以在currentQuestion++之前检查,但是你需要验证currentQuestion0和预期的问题数量之间,这样你就可以保持一个连续的计数

标签: java arrays swing collections


【解决方案1】:

很简单,当nextQuestion 被调用时,你想检查currentQuestion 是否正确

private int correctAnswers = 0;
//...
protected void nextQuestion() {
    timer.stop();
    if (currentQuestion >= 0 && currentQuestion < quiz.size()) {
        Question question = quiz.get(currentQuestion);
        if (question.isCorrect()) {
            correctAnswers++;
        }
    }
    currentQuestion++;
    if (currentQuestion >= quiz.size()) {
        cardLayout.show(panelOfQuestions, "last");
        next.setEnabled(false);
    } else {
        cardLayout.show(panelOfQuestions, Integer.toString(currentQuestion));
        startTime = null;
        next.setText("Next");
        next.setEnabled(true);
        timer.start();
    }
}

【讨论】:

    【解决方案2】:

    这是您的问题的示例解决方案。正是您的原始代码,并进行了一些修改。关键是要明白,您必须随时关联所选答案并填写选择问题的“userResponse”字段。

    很明显,设置它的最佳位置是当用户按下“下一步”按钮时。您检查选中的单选按钮并相应地填写 ChoiseQuestion。

    最后,只需管理测验列表以检查有多少正确的结果。在我的示例中,结果打印在控制台上。

    公共类 QuizMain {

    public static void main(String[] args) {
        new QuizMain();
    }
    
    public QuizMain() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }
    
                List<Question> quiz = new ArrayList<>(5);
                // Couple of conceptual mistakes here.... 
                quiz.add(new ChoiceQuestion("Where is Japan Located?", "Asia", "North America", "Africa", "Europe", "Asia"));
                // There was a mistake, correct answer is 2
                // quiz.add(new ChoiceQuestion("1 + 1:", "2", "4", "3", "1"));
                quiz.add(new ChoiceQuestion("1 + 1:", "2", "4", "3", "2", "1"));
    
                JFrame frame = new JFrame("QUIZ TIME!");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new QuizPane(quiz));
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }
    
    public class QuizPane extends JPanel {
    
        private List<Question> quiz;
    
        private long countdown = 10;
        private Timer timer;
        private JButton next;
        private JButton intro;
    
    
        private CardLayout cardLayout;
        private int currentQuestion;
    
        private JPanel QuestionsPanel;
    
        private Long startTime;
    
        public QuizPane(List<Question> quiz) {
            this.quiz = quiz;
            cardLayout = new CardLayout();
            QuestionsPanel = new JPanel(cardLayout);
            QuestionsPanel.setBorder(new EmptyBorder(40,45,40,45));
    
            JButton start = new JButton("Start");
            start.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    currentQuestion = -1;
                    nextQuestion();
                    timer.start();
                }
            });
    
            JButton intro = new JButton("Instructions");
            intro.addActionListener(new ActionListener() {
              @Override
              public void actionPerformed(ActionEvent e) {
                instructionBox();
              }
            });
    
    
            JPanel mainPanel = new JPanel(new GridBagLayout());
            mainPanel.add(start);
            mainPanel.add(intro);
            QuestionsPanel.add(mainPanel, "start");
    
    
            for (int index = 0; index < quiz.size(); index++) {
                Question question = quiz.get(index);
                QuestionPane pane = new QuestionPane(question);
                question.setButtonGroup(pane.getButtonGroup());
                QuestionsPanel.add(pane, Integer.toString(index));
            }
            QuestionsPanel.add(new JLabel("You have finished the Quiz"), "last");
            currentQuestion = 0;
            cardLayout.show(QuestionsPanel, "Start");
    
            setLayout(new BorderLayout());
            add(QuestionsPanel);
    
            JPanel buttonPane = new JPanel(new FlowLayout(FlowLayout.RIGHT));
            next = new JButton("Next");
            buttonPane.add(next);
            next.setEnabled(false);
    
            add(buttonPane, BorderLayout.SOUTH);
    
            next.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    nextQuestion();
                }
            });
    
            timer = new Timer(250, new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    if (startTime == null) {
                        startTime = System.currentTimeMillis();
                    }
                    long duration = (System.currentTimeMillis() - startTime) / 1000;
                    if (duration >= countdown) {
                        nextQuestion();
                    } else {
                        long timeLeft = countdown - duration;
                        next.setText("Next (" + timeLeft + ")");
                        next.repaint();
                    }
                }
            });
        }
    
        protected void nextQuestion() {
            // store the selected answer for each question
            if (currentQuestion >= 0 && currentQuestion < quiz.size() ) {
                Question currentQObject = quiz.get(currentQuestion);
                if (currentQObject != null) {
                    currentQObject.setUserResponse(getSelected(currentQObject.getButtonGroup()));
                }
            }
            timer.stop();
            currentQuestion++;
            if (currentQuestion >= quiz.size()) {
                cardLayout.show(QuestionsPanel, "last");
                next.setEnabled(false);
                //Show however many correct after last question. 
                //iterate on the collection to count the selected radio buttons
                //What im confused about is really how do i tell the program which (options) are right or wrong. 
                //and if i can do that how do i only count the correct ones. 
                //or for example do i have to take the total questions and subtract by the ones they didnt choose? 
                //a code example on how to do this would be great.
    
                // Just iterate over quiz list to check if answers are correct:
                int totalCorrect = 0;
                for (Question q : quiz) {
                    if (q.isCorrect()) { 
                        totalCorrect++;
                    }
                }
    
                // Show Corrects any way....
                System.out.println("Total correct responses: " + totalCorrect);
    
            } else {
                cardLayout.show(QuestionsPanel, Integer.toString(currentQuestion));
                startTime = null;
                next.setText("Next");
                next.setEnabled(true);
                timer.start();
            }
        }
    
        private String getSelected(ButtonGroup buttonGroup) {
            JRadioButton selectedRadio = null;
            Enumeration e = buttonGroup.getElements();
            while (e.hasMoreElements()) {
                JRadioButton rad = (JRadioButton) e.nextElement();
                if (rad.isSelected()) {
                    selectedRadio = rad;
                    break;
                }
            }
            return selectedRadio.getText();
        }
    
        protected void instructionBox() {
            JOptionPane.showMessageDialog(null,"<html><b><div width='111px' height = '82px' align='justified'> 1.You have limited time to answer each question and your score will be shown at the end of the test. Good Luck!</div></body></html>",
            "Instructions",
            JOptionPane.INFORMATION_MESSAGE);
         }
     }
    
    public interface Question {
    
        public String getPrompt();
    
        public void setButtonGroup(ButtonGroup buttonGroup);
    
        public ButtonGroup getButtonGroup();
    
        public String getCorrectAnswer();
    
        public String[] getOptions();
    
        public String getUserResponse();
    
        public void setUserResponse(String response);
    
        public boolean isCorrect();
    }
    
    public class ChoiceQuestion implements Question {
    
        private final String prompt;
        private final String correctAnswer;
        private final String[] options;
        private ButtonGroup buttonGroup;
    
        private String userResponse;
    
        public ChoiceQuestion(String prompt, String correctAnswer, String... options) {
            this.prompt = prompt;
            this.correctAnswer = correctAnswer;
            this.options = options;
        }
    
        @Override
        public void setButtonGroup(ButtonGroup buttonGroup) {
            this.buttonGroup = buttonGroup;
        }
    
        @Override
        public ButtonGroup getButtonGroup() {
            return this.buttonGroup;
        }
    
        @Override
        public String getPrompt() {
            return prompt;
        }
    
        @Override
        public String getCorrectAnswer() {
            return correctAnswer;
        }
    
        @Override
        public String[] getOptions() {
            return options;
        }
    
        @Override
        public String getUserResponse() {
            return userResponse;
        }
    
        @Override
        public void setUserResponse(String response) {
            userResponse = response;
        }
    
        @Override
        public boolean isCorrect() {
            return getCorrectAnswer().equals(getUserResponse());
        }
    }
    
    public class QuestionPane extends JPanel {
    
        private Question question;
    
        private ButtonGroup buttonGroup = null;
    
        public QuestionPane(Question question) {
            this.question = question;
    
            setLayout(new BorderLayout());
    
            JLabel prompt = new JLabel("<html><b>" + question.getPrompt() + "</b></html>");
            prompt.setHorizontalAlignment(JLabel.LEFT);
    
            add(prompt, BorderLayout.NORTH);
    
            JPanel guesses = new JPanel(new GridBagLayout());
            guesses.setBorder(new EmptyBorder(10,10,10,10));
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.gridwidth = GridBagConstraints.REMAINDER;
            gbc.weightx = 1;
            gbc.anchor = GridBagConstraints.WEST;
    
            List<String> options = new ArrayList<>(Arrays.asList(question.getOptions()));
            //options.add(question.getCorrectAnswer());
            Collections.sort(options);
    
            ButtonGroup bg = new ButtonGroup();
            for (String option : options) {
                JRadioButton btn = new JRadioButton(option);
                btn.setName(option);
                bg.add(btn);
    
                guesses.add(btn, gbc);
            }
            this.buttonGroup = bg;
    
            add(guesses);
        }
    
        public ButtonGroup getButtonGroup() {
            return buttonGroup;
        }
    
        public Question getQuestion() {
            return question;
        }
    
        public class ActionHandler implements ActionListener {
    
            @Override
            public void actionPerformed(ActionEvent e) {
                getQuestion().setUserResponse(e.getActionCommand());
            }
    
        }
    
    }
    

    希望对你有帮助

    【讨论】:

    • 所以,这基本上就是this
    猜你喜欢
    • 1970-01-01
    • 2020-11-09
    • 1970-01-01
    • 2022-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多