Solution 1 :
If you have an array with a lenght from 1-15, your pointer goes from 0-14. 0 is the first element and 14 the last. You get IndexOutOfBoundsException when you try to reach 15.
To create a list between 0 and 14 use:
Random rand = new Random();
List<Integer> rlist = new ArrayList<>();
while (rlist.size() != 15) {
int r = rand.nextInt(15) ;
if (!rlist.contains(r))
rlist.add(r);
}
Problem :
I am doing a quiz and i have a class with String arrays of questions, choises and answers.
On my main class I have empty TextViev and buttons that are updating by a method:
private void updateQuestion(int num){
question.setText(mmQuestionFi.getQuestionFi(num));
answer1.setText(mmQuestionFi.getFiChoice1(num));
answer2.setText(mmQuestionFi.getFiChoice2(num));
answer3.setText(mmQuestionFi.getFiChoice3(num));
answer4.setText(mmQuestionFi.getFiChoice4(num));
mAnswearFi= mmQuestionFi.getCorrectAnswearFi(num);
}
(answer1,2,3,4 – buttons ; mmQestionFi – class where i get data of arrays from)
Then i have a list of random index with a size 15 and from 1 to 15:
Random rand = new Random();
List<Integer> rlist = new ArrayList<>();
while (rlist.size() != 16) {
int r = rand.nextInt(16) ;
if (!rlist.contains(r))
rlist.add(r);
}
I update question at first when the game hasnt started yet.
updateQuestion(rlist.get(index));
And finaly i update my question like
checkNumber++;
if(checkNumber<16){
if(checkNumber==2)
updateQuestion(rlist.get(index+1));
if(checkNumber==3)
updateQuestion(rlist.get(index+2));
if(checkNumber==4)
updateQuestion(rlist.get(index+3));
if(checkNumber==5)
updateQuestion(rlist.get(index+4));
if(checkNumber==6)
updateQuestion(rlist.get(index+5));
if(checkNumber==7)
updateQuestion(rlist.get(index+6));
if(checkNumber==8)
updateQuestion(rlist.get(index+7));
if(checkNumber==9)
updateQuestion(rlist.get(index+8));
if(checkNumber==10)
updateQuestion(rlist.get(index+9));
if(checkNumber==11)
updateQuestion(rlist.get(index+10));
if(checkNumber==12)
updateQuestion(rlist.get(index+11));
if(checkNumber==13)
updateQuestion(rlist.get(index+12));
if(checkNumber==14)
updateQuestion(rlist.get(index+13));
if(checkNumber==15)
updateQuestion(rlist.get(index+14));
( checkNumber initialized before if as int checkNumber=1; 1 – because we update before any user action ( program starts and empty texfields are being filled with data) and only after that it will be updating with if ( when any button is pressed)
So the question is how to get all 15 questions ( get 15 index) and avoid ArrayIndexOutOfBoundsException: length=15; index=15
Thanks in advance!
Comments
Comment posted by Jugjin
That was so easy -_-. Absolutely forgot about start from 0. Thank you once more.