Step 9

Creating the “RandomPicker” class


Next, let’s make another new class. Call it “RandomPicker.”

This class will be used to pick from a list of numbers. This list will start at 0, and we will be able to add more numbers to this list as needed, numbers will be added sequentially with the next number being the next whole number. (For example: [0,1,2,3,4,5])

Importing packages


The first thing we need to do is add some packages to this class. Copy the code as shown to do this.

A package is an external group of code that we can use to help us within our own code.

The ArrayList package will allow us to use the ArrayList class. This class gives us the ability to have a list of items as one variable.

The Random package will allow us to do things involving randomness, like picking a random number.

Adding class variables


Next add the following code to create some class variables for the “RandomPicker” class.

We’ve done this before, but we never said the name. A class variable is a variable that can be accessed anywhere inside the class. Because these variables are not within any functions, they are created as class variables.

Here we have two. An ArrayList of Integers called “numberList” and a single int called “toAdd”. The “numberList” will be used to contain our list of numbers to pick from. The “toAdd” variable will be used to keep track of what the next number we need to add to our list is, we start it at 0 since 0 should be the first number we have to add.