Android random number

I generate one random card from an array. and assign it. "The code is below ... but it shows 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); 
}
+3
source share
2 answers

b - int

so you need a rank [b] array at some point in your code

According to your code, perhaps it should read showcard1.setBackgroundResource (rank [b]);

+4
source

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

+3
source

Source: https://habr.com/ru/post/1756122/


All Articles