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 like this.
public class Facts {
String facts[] = {
"Elephants are the only mammals that can't jump.",
"Candles will burn longer and drip less if they are placed in the freezer a few hours before using.",
"Potatoes have more chromosomes than humans.",
"You burn more calories sleeping than you do watching television.",
"Animals that lay eggs don't have belly buttons.",
};
String factNumber[] = {
"Fact 1",
"Fact 2",
"Fact 3",
"Fact 4",
"Fact 5",
};
public String randomButton() {
Random r = new Random();
return facts[i]
}
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:
Example:
public String randomButton() {
Random random = new Random();
return facts[random.nextInt(facts.length)];
}
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)];
Try this also
private Integer a = 0;
public String randomButton() {
Random random = new Random();
a = random.nextInt(facts.length);
}
String factNumber = facts.a;