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. For instance, maybe our app wants to show a random tip of the day, or is a game that has to choose between scenarios, or is a quiz that asks random questions.
The Random
class is part of the Java API and is fully compatible with 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 in a certain range. This next 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...