Java 获取错误:索引3超出长度3错误的界限,即使它应该在数组界限内

Java 获取错误:索引3超出长度3错误的界限,即使它应该在数组界限内,java,arrays,database,arraylist,Java,Arrays,Database,Arraylist,我有一个测验应用程序,我正在尝试为一个大学项目创建,在上一个屏幕中,我问用户想为测验做多少个问题。从那里,我从问题数据库中随机挑出3个问题,如你所见 try { connection = DriverManager.getConnection("jdbc:sqlite:src/quiz"); PreparedStatement addQuestion = connection.prepareStatement(&

我有一个测验应用程序,我正在尝试为一个大学项目创建,在上一个屏幕中,我问用户想为测验做多少个问题。从那里,我从问题数据库中随机挑出3个问题,如你所见

        try {
            connection = DriverManager.getConnection("jdbc:sqlite:src/quiz");
            PreparedStatement addQuestion = connection.prepareStatement("SELECT question_ID FROM questions");
            rs = addQuestion.executeQuery();
            ArrayList<Integer> quizID = new ArrayList<>();
            while (rs.next()) {
                quizID.add(rs.getInt("question_ID"));
            }
            for (int i = 0; i < amountQuestions; i++) {
                Random rand = new Random();
                questions.add(quizID.get(rand.nextInt(quizID.size())));
            }
        } catch (SQLException error) {
            System.err.println(error.getMessage());
        }
我回答了两个问题,就好像程序为我完成了测验一样。在错误显示之前,我无法单击“下一步”按钮


您从未检查过
count>=questions.size()
,因此您当然会得到
索引自动边界异常。请注意,在您的
ActionListener
中,您在呈现问题之前增加了计数(用作索引),因此问题1将使用索引1,问题2将使用索引2,依此类推。请记住,数组和列表是零索引的,因此第三个问题(尝试访问索引3)自然会失败

您可能希望将
count++
移动到
renderQuestions()
之后,并在某个地方添加一个检查,以便在您没有问题时进行检查(可能只有我一个人,但我从未看到您检查
count

    private void renderQuestions() {
        System.out.println(questions);
        System.out.println(questions.size());
        System.out.println(count);
        try {
            connection = DriverManager.getConnection("jdbc:sqlite:src/quiz");
            PreparedStatement addQuestion = connection.prepareStatement("SELECT * FROM questions WHERE question_ID = ?");
            addQuestion.setInt(1, questions.get(count));
            rs = addQuestion.executeQuery();
            while (rs.next()) {
                ...
            }
            button1.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    userAnswer = buttonGroup.getSelection().getActionCommand();
                    count++;
                    renderQuestions();
                }
            });
        } catch (SQLException error) {
            System.err.println(error.getMessage());
        }
    }