![](/img/trans.png)
[英]Array index out of bounds error even though the indices are within the array length
[英]Getting Error: Index 3 out of bounds for length 3 Error | Even though it should be within Array Bounds
我有一個正在嘗試為大學項目創建的測驗應用程序,在上一個屏幕中,我詢問用戶想為測驗做多少問題。 從那里我從問題數據庫中隨機挑選出 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());
}
然后在下面的代碼上。 我得到了這些問題,然后當用戶單擊按鈕時,我將計數增加 1 並重新運行該方法。
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());
}
}
我回答了兩個問題,就像程序為我完成了測驗。 在錯誤顯示之前,我無法單擊下一步按鈕。
你從來沒有檢查過count >= questions.size()
,所以你當然會得到一個IndexOutOfBoundsException
。 請注意,在您的ActionListener
中,您在呈現問題之前增加了計數(用作索引),因此問題 1 將使用索引 1,問題 2 將使用索引 2,依此類推。 請記住 arrays 和列表是零索引的,因此嘗試訪問索引 3 的第三個問題自然會失敗。
您可能希望將count++
移動到renderQuestions()
之后,並在您用完問題時在某處添加檢查(可能只是我,但我沒有看到您檢查過count
)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.