ejdhdd ejdhdd
ejdhdd ejdhdd

Reputation: 1

SetImageResource random value not work

I want to get RANDOM value in my function, But n always equals 0. What am I doing wrong?

    image = (ImageView) findViewById(R.id.imageView1);
    //блок Random
    Log.d(Tag, "1");
    int NUM_IMAGES=7;
    int imageArr[] = new int[NUM_IMAGES];
    Log.d(Tag, "2");
    imageArr[0] = R.drawable.image1;
    imageArr[1] = R.drawable.image2;
    imageArr[2] = R.drawable.image3;
    imageArr[3] = R.drawable.image4;
    imageArr[4] = R.drawable.image5;
    imageArr[5] = R.drawable.image6;
    imageArr[6] = R.drawable.image7;

    Log.d(Tag, "3");
    int n = (int)Math.random()*NUM_IMAGES;
    Log.d(Tag, "n="+n);
    image.setImageResource(imageArr[n]);

Upvotes: 0

Views: 169

Answers (2)

Dalmas
Dalmas

Reputation: 26547

(int) Math.random() is executed first and will always return 0. Then multiplying NUM_IMAGES by 0 still returns 0.

You should add brackets around your expression so the conversion to int will be done after the multiplication :

int n = (int) (Math.random()*NUM_IMAGES);

Upvotes: 1

Shobhit Puri
Shobhit Puri

Reputation: 26007

If you read here, the priority of type cast is more than that of multiplication. Also the priority of ()(bracket) is higher than that of type cast. So the right way might be to put multiplication in bracket so that multiplication happens before casting. Something like:

int n = (int)(Math.random() * NUM_IMAGES);

Notice the brackets. Hope this helps.

Upvotes: 0

Related Questions