Habenero Java

Click here for the previous tutorial.

Random works very similarly to the Scanner. Try this to start:

Random random = new Random();

From what you have learned from experience, you may have already known to import it. If you have not yet:

import java.util.Random;

Now to actually use it, though. Assigning a random number to an integer is actually even easier than it was with Scanner, because we do not need to validate. The computer will not pass you anything that you do not want.

int randomInteger = 0 + random.nextInt(9);

In this, we have assigned randomInteger to be of value between 0 and 8. I am hoping you are a bit confused by the odd syntax. No matter, I will explain it anyway. Simply put, the 9 within the parenthesis tells the computer that there are nine numbers to choose from. Computers love to start counting from zero, it is like cake to them. So if there are nine numbers, and it starts at zero, then the numbers will be 0, 1, 2, 3, 4, 5, 6, 7, and 8. 9 is not included, because in this case that would be a tenth number. If you wanted the inclusive set of numbers zero to nine, you could have typed a 10 instead.

There is another common solution if nine is needed in the set, and especially if the presence of zero was undesired, which is to shift it one. This is why zero was inluded in the original declaration. It can simply be replaced by the amount that the number needs to be shifted. In more simple terms, whatever number you replace zero with will be the minimum value that will be returned. Whatever number replaces nine, will be the size of the pool of random integers.

Click here to coninue to the next tutorial.