tags:

views:

74

answers:

1

I m generating one random card from array. and assigning it.' Below is the code..but its is showing an error. What is the problem?

public void rand() {
    String rank[]=  {"tclub1.png", "tclub2.png", "tclub3.png", "tclub4.png", "tclub5.png", "tclub6.png", "tclub7.png", "tclub8.png", "tclub9.png", "tclub10.png","tclub11.png", "tclub12.png", "tclub13.png"};

    Random randInt = new Random();

    int b = randInt.nextInt((rank.length));
    showcard1.setBackgroundResource(b); 
}
+1  A: 

Try changing to int b = randInt.nextInt((rank.length)) - 1; (because rank.length = 13 and your array is indexed from 0 to 12)

Regards from France ;)

Squ36
`int b = randInt.nextInt(rank.length-1);` is slightly better ;-) (otherwise you *probabaly* get a -1 index)
Andreas_D
I don't know Java, so I could be wrong here, but usually a rand(max) function will generate a number between 0 and max-1 already. Otherwise, rand(10) could generate 11 possible values, which is almost never what you want.
Ed Swangren
Ed is right. Random.nextInt(n) - nextInt will generate values in this range [0, n> - This means that 0 is inclusive while n is exclusive. Therefore, by setting n to the length of the array, the generated values will not be out of the array's bounds. JavaDoc: http://download.oracle.com/docs/cd/E17409_01/javase/6/docs/api/java/util/Random.html#nextInt(int)
John
My bad, sorry for that :p
Squ36