3
/*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 !

  • Maybe check: http://stackoverflow.com/questions/5533191/java-random-always-returns-the-same-number-when-i-set-the-seed I think you need to share the Random() instance across the whole class. – quangson91 Nov 05 '15 at 09:52

2 Answers2

5

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.

Dhaval Patel
  • 10,119
  • 5
  • 43
  • 46
  • @FrankN.Stein not understood. As per [doc](http://docs.oracle.com/javase/7/docs/api/java/util/Random.html#nextInt%28int%29) r.nextInt(index) will generate value 0 (inclusive) and the specified value (exclusive). so for index 199 it will generate between 0 to 198 and +1 means 1 to 199. isn't it true? – Dhaval Patel Nov 05 '15 at 10:13
  • Right, overlooked your answer. – Phantômaxx Nov 05 '15 at 10:31
0

A random number generated by nextInt should be a multiple of 200 at random, i.e. one every 200 or so. This test suggests this is happening correctly:

public void test() {
    Random random = new Random();
    final int tests = 200000;
    int twoHunderdIsAFactor = 0;

    for (int i = 0; i < tests; i++) {
        if (random.nextInt() % 200 == 0) {
            twoHunderdIsAFactor += 1;
        }
    }
    System.out.println("Tests = " + tests + " Hits = " + twoHunderdIsAFactor + " Proportion = " + (tests / twoHunderdIsAFactor));
}

prints Tests = 200000 Hits = 1012 Proportion = 197 - i.e. about 200 times for 200000 randoms.

Generating randoms in a specific range is dealt with in other answers.

OldCurmudgeon
  • 64,482
  • 16
  • 119
  • 213