[英]IndexOutOfBoundsException when creating instance of JAXBContext
[英]IndexOutOfBoundsException when creating an object (Java)
我正在做一個問答游戲,它將從文本文件中讀取許多問題及其各自的答案。 首先將它們放入ArrayList中,然后將每個問題轉換為單獨的問題對象。 在程序的這一部分中,我收到了IndexOutOfBoundsException。
文本文件的格式如下:
題
正確答案
錯誤答案1
錯誤答案2
錯誤答案3
(EMPTYLINE)
問題2
...
...
...
使用bufferedReader在稱為IO的類中處理文本文件。 這些問題存儲在ArrayList>中,以便每個問題分開存儲。 在稱為問題的類中,我有一個用於從ArrayList創建對象的方法。
代碼如下:
public class Questions
{
private ArrayList<ArrayList<String>> originalList;
private ArrayList<SingleQuestion> newList;
private ArrayList<SingleQuestion> objectList;
private IO io;
public Questions(){
io = new IO(); //Creates a new instance of IO.
objectList = new ArrayList<SingleQuestion>();
createQuestions();
}
public void createQuestions(){
originalList = io.getArray();
for(int i = 0; i < originalList.size(); i++)
{
objectList.add(new SingleQuestion(originalList.get(i)));
}
}
SingleQuestion類的構造函數是這樣的:public class SingleQuestion {private String question; 私有字符串correctAnswer; 私有字符串answer2; 私有字符串答案3; 私有字符串答案4;
public SingleQuestion(ArrayList<String> questionArray){
this.question = questionArray.get(0);
this.correctAnswer = questionArray.get(1);
this.answer2 = questionArray.get(3);
this.answer3 = questionArray.get(4);
this.answer4 = questionArray.get(5);
}
當代碼到達SingleQuestions構造函數的最后時,我得到了IndexOutOfBoundsException。
該錯誤消息如下所示:
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 5, Size: 5
at java.util.ArrayList.rangeCheck(Unknown Source)
at java.util.ArrayList.get(Unknown Source)
at MVC_test.SingleQuestion.<init>(SingleQuestion.java:21)
at MVC_test.Questions.createQuestions(Questions.java:47)
at MVC_test.Questions.<init>(Questions.java:20)
at MVC_test.GModel.<init>(GModel.java:23)
at MVC_test.GMain.main(GMain.java:7)
this.question = questionArray.get(0);
this.correctAnswer = questionArray.get(1);
this.answer2 = questionArray.get(3);
this.answer3 = questionArray.get(4);
this.answer4 = questionArray.get(5);
應該
this.question = questionArray.get(0);
this.correctAnswer = questionArray.get(1);
this.answer2 = questionArray.get(2);
this.answer3 = questionArray.get(3);
this.answer4 = questionArray.get(4);
您跳過了questionArray.get(2)
。 索引只會上升到4。
好像您忘記了號碼...
public SingleQuestion(ArrayList<String> questionArray){
this.question = questionArray.get(0);
this.correctAnswer = questionArray.get(1);
this.answer2 = questionArray.get(3);
this.answer3 = questionArray.get(4);
this.answer4 = questionArray.get(5);
}
該列表只有五個條目,所以questionArray.get(5);
會給你一個例外。 您永遠不會使用第三個元素(索引2)。
Java方法和類通常以0索引 :這意味着第一個元素是元素編號0,第二個元素是元素編號1, ArrayList
。因此對於ArrayList
,其中有5個元素(顯然是size() == 5
),最后一個元素實際上是5-1
或4 。 由於此行,您將獲得IndexOutOfBoundsException
:
this.answer4 = questionArray.get(5);
您想要的是:
this.answer4 = questionArray.get(4);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.