Random+Numbers

A **__random number__** is a number that is randomly selected in a range that you want.

Here are the set of codes you need to memorize in order to use the random generator: Random generator = new Random; - This code is used to set the variable for random generator. generator.nextInt - This is the code that makes the random number. For example, if you input 5 in the parenthesis, the generator will randomly select a number between 0 and 4 which are 5 numbers (0, 1, 2, 3, 4).

generator.nextInt(5) > Chooses a number between 0 - 4. generator.nextInt(10) > Chooses a number between 0 - 9. generator.nextInt(100) > Chooses a number between 0 - 99.
 * EX.**

How to use the code:

1. Set the random variable - Random generator = new Random; Usually, it will be set on the top where you set all the variables, but you can change it depending on where you want to use it.

2. Use the Random generator to make a random number - generator.nextInt.

So this is how it will look when you finish making the code:

code import java.util.Random; //you always have to make sure to type this line //when using Random generator. public class RandomNumber { public RandomNumber {     Random generator = new Random; generator.nextInt(5); } }

code

//If a number not beginning in 0 is wanted, one should use the plus sign (+) with some number. Example: generator.nextInt(5) + 5;// this would create a number 5-9 because it adds 5 to whatever number that the generator creates So now for some practice problems... Note: The code below does not have import statement and the class to save space and make this shorter. Remember that the import statement is needed in order to generate random numbers. Assume that the class is RandomNumber.

Problem: Create a number between 25 and 99. public RandomNumber {

}

Answer: public RandomNumber { generator.nextInt(75) + 25;** ////generator creates # between 0-74 and 25 is added to it }//
 * Random generator = new Random;

Problem: Create a number 5 through 11. public RandomNumber //{

}//

Answer public RandomNumber //{// generator.nextInt(7) + 5;** ////generator creates # 0-6 and 5 is added to it// }
 * Random generator = new Random;

The minus sign ( - ) can also be used to offset random numbers in the same way. generator.nextInt(10) - 20; //generator creates a number 0-9 then 20 is taken from it to create number between -20 and -11


 * A helpful method in Objectdraw that may be used in loops is the 'int nextValue' method. This returns the next random number after going through the loop.