Step 10

Creating a constructor


Next, add the following code to your “RandomPicker” class. When you see the name of the class followed by (), it looks a lot like a function. This is something called a constructor.

Whenever you create a new piece of data, the constructor is used to create that data. Remember using the new keyword earlier, this was us using the constructor to create a new piece of data.

Every time we construct a new piece of data, we say we are creating a new instance of the class. For example, if I had a “Dog” class, every living dog would be an instance of a “Dog.”

The reason we need a constructor is that sometimes we need some code to run when an instance is created. In this constructor we need to create a new instance of an ArrayList in order to have the “numberList” variable. We also add the number 0 to the list, and make “toAdd” equal to 1. This way, every time we create a new “RandomPicker” instance it will always start with the number 0 inside it.

Adding to the list


Next, add the following code to create the “addOneToList” function.

This function will add the next number to the list, and update the “toAdd” variable to go up by 1.

Picking a random number


Next, add the following code to create the “pickRandomNumber” function.

We first create a new instance of the Random class so we can use it in the next line.

Then we use the “nextInt” function which returns a random number between 0 and the number given as a parameter. For the parameter, we put the size of the list (how many numbers are in the list). For example, if we have 3 numbers in the list, this would translate to “nextInt(3).”

Then we use the “get” function and the to pick a random number from “numberList” using the randomly generated number from the previous line.

Lastly, we print out the random number that was picked!