A random diversion
Sometimes in our apps, we will want a random number and Java provides us with the Random
class for these occasions. There are many possible uses for this class; perhaps our app wants to show a random tip-of-the-day or a game that has to choose between scenarios, or a quiz that asks random questions.
The Random
class is part of the Java API and is fully compatible in our Android apps.
Let's have a look at how we can create random numbers, and later in the chapter we will put it to practical use. All the hard work is done for us by the Random
class. First, we need to create an object of type Random
.
Random randGenerator = new Random();
Then we use our new object's nextInt
method to generate a random number between a certain range.
This line of code generates the random number using our Random
object and stores the result in the ourRandomNumber
variable:
int ourRandomNumber = randGenerator.nextInt(10);
The number that we enter for the range starts from zero. So the...