Java 我如何计算正确选择的JRadioButton并打印总计;分数;?

Java 我如何计算正确选择的JRadioButton并打印总计;分数;?,java,arrays,swing,collections,Java,Arrays,Swing,Collections,我的申请是一个多选项测验。现在只有两个问题,所以我可以测试逻辑,但在我弄明白后,我会加起来100。实际上,我有一个新的框架,其中按钮添加到面板,然后面板添加到JFrame。然后,我使用nextQuestion()方法,只要还有问题,我就可以回答多个问题。而且,我在他们的方法中还设置了一个计时器,每个问题都有10秒的时间 protected void nextQuestion() { timer.stop(); currentQues

我的申请是一个多选项测验。现在只有两个问题,所以我可以测试逻辑,但在我弄明白后,我会加起来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());
            }

        }

    }

}
受保护的void nextQuestion(){
timer.stop();
当前问题++;
如果(currentQuestion>=quick.size()){
cardLayout.show(问题栏,“最后一个”);
next.setEnabled(false);
//在最后一个问题之后显示正确的数量。
//在集合上迭代以计数选定的单选按钮
//我真正困惑的是我如何告诉程序哪些选项是对的或错的。
//如果我能做到这一点,我怎么才能只计算正确的。
//或者举例来说,我是否必须把所有的问题减去他们没有选择的问题?
//一个关于如何做到这一点的代码示例将非常好。
}否则{
cardLayout.show(QuestionsPanel,Integer.toString(currentQuestion));
startTime=null;
next.setText(“next”);
next.setEnabled(true);
timer.start();
}
}
公共接口问题{
公共字符串getPrompt();
公共字符串getCorrectAnswer();
公共字符串[]getOptions();
公共字符串getUserResponse();
公共void setUserResponse(字符串响应);
公共布尔值isCorrect();
}
公共类选择问题实现问题{
私有最终字符串提示符;
私人最终答案;
私有最终字符串[]选项;
私有字符串用户响应;
公共选项问题(字符串提示、字符串更正回答、字符串…选项){
this.prompt=prompt;
this.correctAnswer=correctAnswer;
this.options=选项;
}
@凌驾
公共字符串getPrompt(){
返回提示;
}
@凌驾
公共字符串getCorrectAnswer(){
返回正确答案;
}
@凌驾
公共字符串[]getOptions(){
返回选项;
}
@凌驾
公共字符串getUserResponse(){
返回userResponse;
}
@凌驾
公共void setUserResponse(字符串响应){
用户响应=响应;
}
@凌驾
公共布尔值isCorrect(){
返回getCorrectAnswer().equals(getUserResponse());
}
}
公共类问题窗格扩展了JPanel{
私人问题;
公共问题窗格(问题){
这个问题=问题;
setLayout(新的BorderLayout());
JLabel prompt=newjlabel(“+question.getPrompt()+”);
prompt.setHorizontalAlignment(JLabel.LEFT);
添加(提示,BorderLayout.NORTH);
JPanel guesses=newjpanel(newgridbaglayout());
猜测。设定顺序(新的空顺序(10,10,10,10));
GridBagConstraints gbc=新的GridBagConstraints();
gbc.gridwidth=GridBagConstraints.rements;
gbc.weightx=1;
gbc.anchor=GridBagConstraints.WEST;
List options=newarraylist(Arrays.asList(question.getOptions());
options.add(question.getCorrectAnswer());
集合。排序(选项);
ButtonGroup bg=新建ButtonGroup();
用于(字符串选项:选项){
JRadioButton btn=新的JRadioButton(选项);
bg.add(btn);
猜测。添加(btn、gbc);
}
添加(猜测);
}
公共问题{
返回问题;
}
公共类ActionHandler实现ActionListener{
@凌驾
已执行的公共无效操作(操作事件e){
getQuestion().setUserResponse(如getActionCommand());
}
}
}
}

所以实际上,我只是有一个问题,做那个小的if-else代码块。如果你们能帮我的话。我对迭代集合有了一些想法,尽管我不知道如何做。这些只是我使用的类和我遇到问题的方法。

下面是一个解决问题的示例。就是您的原始代码,经过一些修改。关键是要理解,您必须随时关联所选答案,并填写选择问题的“userResponse”字段

显然,最好的设置位置是用户按下“下一步”按钮。选中选中的单选按钮并相应地填写选项

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

公开课{

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

    }

}
publicstaticvoidmain(字符串[]args){
新奎兹曼();
}
公共QuizMain(){
invokeLater(新的Runnable(){
@凌驾
公开募捐{
试一试{
UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
}catch(ClassNotFoundException |实例化Exception | IllegalacessException |不支持ookandfeelException ex){
例如printStackTrace();
}
列表测验=新数组列表(5);
//这里有几个概念上的错误。。。。
新的选择题:“日本在哪里?”,“亚洲”,“北美”,“非洲”,“欧洲”,“亚洲
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();
    }
}