Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

value zero generated numerously using random function() [duplicate]

Tags:

java

android

/*This is my function code*/
Random random = new Random();
int randomInt = random.nextInt()%200;

String imgName = "img" + randomInt;

int ImageId = getResources().getIndentifier(imgName,"drawabale",getPackageName());
myImage.setImageResourse(ImageId);   

Previously in my drawable folder there are 200 images already inserted using img1,img2.....img199 like nomenclature... every time I call random function mention below to generated one random number and form a string name starting from "img" and some number. But most of time only 0 is generated by random function and id set to image is display 0th image constantly..at some point it successfully display other images but most of time it generated zero value continuosly.

Thanks in Advance !

like image 234
Kamalakar Thakare Avatar asked May 12 '26 11:05

Kamalakar Thakare


1 Answers

You can generate Random number with specific Range

Random r = new Random();
int randomInt = r.nextInt(maxVal - minVal) + minVal

For your example

 int randomInt = r.nextInt(200 - 1) + 1

Will generate number between 1 to 199.

like image 157
Dhaval Patel Avatar answered May 14 '26 03:05

Dhaval Patel