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
Use the random class. That class has a method, the nextInt(int n)
(doc) and quote:
Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive), drawn from this random number generator's sequence. The general contract of nextInt is that one int value in the specified range is pseudorandomly generated and returned. All n possible int values are produced with (approximately) equal probability...
So, you need a random number that is in fact a random fact, so generate a random number between zero and the facts array size:
public String randomButton() {
Random random = new Random();
return facts[random.nextInt(facts.length)];
}
Try this also
private Integer a = 0;
public String randomButton() {
Random random = new Random();
a = random.nextInt(facts.length);
}
String factNumber = facts.a;
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)];