创建对象时的IndexOutOfBoundsException(Java)

时间:2014-02-21 17:17:37

标签: java arraylist converter indexoutofboundsexception

我正在制作一个测验游戏,它将从文本文件中读取一些问题及其各自的答案。首先将它们放入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类构造函数如下:     公共类SingleQuestion {     私有字符串问题;     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);
}

当代码到达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)

4 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:1)

您跳过了questionArray.get(2)。该指数最多只能达到4。

答案 2 :(得分:1)

看起来你忘记了一个号码......

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)。

答案 3 :(得分:1)

Java方法和类通常为0索引:这意味着第一个元素是元素编号0,第二个元素是元素编号1,等等。那么对于ArrayList,其中你有5个元素(显然是size() == 5),最后一个元素实际上是5-1,或 4 。由于这一行,您将获得IndexOutOfBoundsException

this.answer4 = questionArray.get(5);

你想要的是:

this.answer4 = questionArray.get(4);