I am making a quiz-game that will read a number of questions and their respective answers from a text file. These are first put into an ArrayList but then each question is to be converted into a separate question-object. It is during this part of the program I receive an IndexOutOfBoundsException.
The textfile is formatted in the following way:
Question
Correct Answer
Wrong Answer1
Wrong Answer2
Wrong Answer3
(emptyline)
Question2
...
...
...
The textfile is handled in a class called IO using a bufferedReader. The questions are stored in an ArrayList> so that each question is stored separate.
In a class called questions I have a method used for creating objects from the ArrayList.
The code looks like this:
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)));
}
}
The SingleQuestion class constructor like this:
public class SingleQuestion {
private String question;
private String correctAnswer;
private String answer2;
private String answer3;
private String answer4;
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);
}
When the code reaches the very end of SingleQuestions constructor I get an IndexOutOfBoundsException.
The error message looks like the following:
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)