简体   繁体   中英

random selection from array

I have this block of code below which is to control questions which are to be displayed from the array. I am having problem with the the 3rd line of code, an i am not entirely sure what the problem is.

rnd1, rnd2 are both double. Eclipse is telling me that rnd2 should be an int. however i was advised that the rnd's should be double for the ceiling function to work. ques is a text field. questions is the array.

 rnd1 = Math.ceil(Math.random()*3);
 rnd2 = Math.ceil(Math.random()*questions.length)-1;
 ques.setText(questions[rnd2]);

Im basing this on action script which i used for a quiz application. It is used to pick out the question from the question array randomly.

rnd1=Math.ceil(Math.random()*3);
rnd2=Math.ceil(Math.random()*questions.length)-1;
q.text=questions[rnd2];
if(questions[rnd2]=="x")
{
  change_question();
}
questions[rnd2]="x";
enable_disable(1);

You need to select an element of an array with an int so make rnd2 an int and cast the ceiling function (if you really need it, if you cast just the random it'll truncate the decimal places off) like so:

rnd2 = (int)Math.ceil(Math.random()*questions.length)-1;

Just make sure to declare rnd2 as an int not double

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM