2014-02-21 27 views
0

我正在製作一個測驗遊戲,它將從文本文件中讀取許多問題及其各自的答案。它們首先被放入一個ArrayList中,然後每個問題都被轉換成一個單獨的問題對象。正是在這部分程序中,我收到了一個IndexOutOfBoundsException。創建對象時的IndexOutOfBoundsException(Java)

文本文件按以下方式格式化:

問題
正確答案
錯誤的正確答案爲
錯誤ANSWER2
錯誤ANSWER3
(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) 

回答

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

如何我傻的!非常感謝! – xsiand

1

你跳過questionArray.get(2)。該指數僅上升到4

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

1

Java方法和類通常是0索引:這意味着,所述第一元素是元素數目0,第二個元素是元素數目1,等等。因此,對於你ArrayList,在這裏有5個元素(它顯然size() == 5),最後的元素實際上是5-1或。你得到了IndexOutOfBoundsException,因爲這行:

this.answer4 = questionArray.get(5); 

你想要的是:

this.answer4 = questionArray.get(4);