Android Build a Simple Android App with Java Testing and Debugging Wrapping Up

Mark Ji
Mark Ji
675 Points

Some improvements

For this app, how can i make the facts appear in sequence I want instead of randomly generated ?

1 Answer

Luke Strama
Luke Strama
6,926 Points

Once you have the facts in the order that you want them, just get it to run through the index using a 'number' variable and adding 1 to it. Once you get to the last value, it restarts to index 0 and goes again. Not setting it back to 0 crashes the app because it runs out of elements in the array.

I left the random version commented out for reference.

public class FactBook {
    // Fields or Member Variables - Properties about the object
    private String[] facts = {
            "Ants stretch when they wake up in the morning.",
            "Ostriches can run faster than horses.",
            "Olympic gold medals are actually made mostly of silver.",
            "You are born with 300 bones; by the time you are an adult you will have 206.",
            "It takes about 8 minutes for light from the Sun to reach Earth.",
            "Some bamboo plants can grow almost a meter in just one day.",
            "The state of Florida is bigger than England.",
            "Some penguins can leap 2-3 meters out of the water.",
            "On average, it takes 66 days to form a new habit.",
            "Mammoths still walked the earth when the Great Pyramid was being built." };

    // Methods - Actions the object can take

    private int number = 0;

    public String getFact() {
        // Randomly select a fact
        /*Random randomGenerator = new Random();
        int randomNumber = randomGenerator.nextInt(facts.length);
        return facts[randomNumber];
        if (number < facts.length-1) {
        else {
            number = 0;
        return facts[number];
Mark Ji
Mark Ji
675 Points

thx a lot! I was thinking about adding a counter in the "mainactivity" class, but found the value fail to update each time I click the button. Defining a private counter in "Factbook" class is clear and reasonable !

Mohammed Safiulla D
Mohammed Safiulla D
12,453 Points

is not just "if (number < facts.length)" enough? I don't think you need a -1 as you can never see the last fact.