Week 8, Notes 2

Random

·       “random” numbers from a computer are not really random.   We call them pseudo-random numbers.

·       pseudo-random numbers are generated from a seed value.

·       The first pseudo-random number is the seed value itself.

·       The second is generated by applying a random number algorithm to the seed value.  The algorithm produces a result, and this result is the second pseudo-random number.

·       The third is generated by applying a random number algorithm to the second pseudo-random number.  The algorithm produces a result, and this result is the third pseudo-random number.

 

If you start with the same seed value, you always get the same set of pseudo-random numbers.

 

In java, the generator is object is created from the class Random.

One of the Random constructors takes a parameter that is the seed of the sequence this Random object will generate.

The other important Random constructor does not take a seed value.  Instead it uses the current time (expressed as an integer) as the seed value.

 

In either case, to get the second random number, call the nextInt() method of your random number generator object.

 

Write a method that will:

declare and initialize a local variable containing a Random object.  Supply the seed 5 to this constructor.

loop – inside the loop, generate and print 5 random numbers.

 

Modify the method to use the Random constructor that takes no parameters.

 

for loops

Useful when you know (or can find out) exactly how many times you need to go through the loop.

 

‘Automatically’ does the incrementing that must be done by hand in a while loop.

 

for (<loop counter initialization stmt> ;

<conditional expression> ;

<post body action stmt>)

{

<loop body>

}

 

<loop counter initialization stmt> executed only once – before anything else related to the loop is done

<conditional expression> is evaluated at the beginning of the loop every time through the loop

<post body action stmt> executed at the end of the loop body everytime the loop body is executed.

Flow chart for a for loop

Here is the control flow chart for a for loop.

Example

    public void myMeth(int in)

    {

        // for loop for the number of times passed in

        for (int i = 0;

            i < in;

            i++)

        {

            System.out.println(i);

        }

    }

 

See demos/W08N03.java (W08N03.java uses a for loop to print Random numbers)