Randomizing text file read in Java

前端 未结 4 2079
春和景丽
春和景丽 2021-01-18 11:32

I am trying to read a text file in Java, basically a set of questions. With four choices and one answer. The structure looks like this:

question

o

4条回答
  •  渐次进展
    2021-01-18 12:18

    Other people (Mike, Erick) have already suggested better approaches to this problem by creating a new Question class, adding questions to a collection, and using the shuffle method to randomize them.

    Regarding why you are "getting a null" in your code: As far as I can see in your example code you are only reading two questions from the file:

    for (ar=0;ar<2;ar++) {
        [...]
    }
    

    This means that positions 0 and 1 in your arrays will have valid data, while positions 2 to 49 will contain null.

    Later when you try to randomize questions you call your random method like this:

    int ran = random(1,25);
    

    This returs a value between 1 and 25, which you then use as an array index.

    If this index happens to be '1' you'll be alright. For all other cases (2 to 25) you'll be accessing null values in your arrays, and getting exceptions when trying to play with these values.

提交回复
热议问题