Getting a random value from an array

后端 未结 3 1834
Happy的楠姐
Happy的楠姐 2021-01-28 07:38

I have a simple app that generates facts. I would like to incorporate a function that generates a random fact instead of incrementing of decrementing.

My array looks lik

3条回答
  •  广开言路
    2021-01-28 08:10

    Simple! Method nextInt(facts.length) returns a random integer between 0 and the length of array. Put it as the index of the array to get the random one:

    Random rnd = new Random()
    String randomFact = facts[rnd.nextInt(facts.length)];
    

提交回复
热议问题