03 Math and Arrays

In Java the Math.random() method returns a random number between 0 and 1. You can get a random number between 0 and 5 using Math.random() * 5. To get an Integer you need to add the Math.floor() method:

Math.floor(Math.random() * 9 + 1) produces an Integer between 1 and 10.

Math.floor(Math.random() * A + B) produces an Integer between B and (A+B).

Like all other programming languages, Java needs to declare arrays before you can use them. This is done with the new Array method:

array1 = new Array(5);

The example makes an array called array1 and gives it 5 elements.

Lets load an array with 100 random numbers.

var sum=0;

rnums = new Array(100);

for (i = 0; i< 100; i++)

{

rnums[i]=Math.floor(Math.random() * 99 + 1);

document.write(rnums[i] + " ");

sum = sum + rnums[i];

}

document.write("<br>" + "The total is " + sum);

avg = sum/100;

document.write("<br>" + "The average is " + avg);

-create a variable called sum and set the value to 0

-create an array called rnums and give it 100 cells

-start a for loop that will run 100 times

-each cell in the array is filled with a random integer between 1 and 100

-print the random number to the screen

- keep a running total of all the random numbers

- loop

- print the total to the screen

- calculate the average

- print the average to the screen

This is what the script output looks like:

88 38 61 39 90 28 46 59 41 31 17 59 15 83 16 57 53 2 50 86 68 77 28 96 80 32 13 89 57 38 42 86 66 7 58 46 88 33 18 83 65 90 88 37 99 29 62 39 92 81 23 79 33 94 45 50 83 16 95 43 84 12 33 30 70 37 66 10 61 83 56 16 2 83 26 90 34 57 4 89 16 25 87 9 51 27 72 94 99 29 28 86 79 15 69 88 82 7 55 88

The total is 5356

The average is 53.56

Review

    • Math.random() returns a random number between 0 and 1

    • Math.floor(x) returns the integer value of x

    • Math.floor(Math.random() * A + B) produces an Integer between B and (A+B)

    • arrayname = newArray(y) produces a new array called arrayname with y cells

      • array positions are numbered from 0 to y-1.

      • a 5 cell array called fish is addressed fish[0], fish[1], fish[2], fish[3], fish[4].

    • var declares a variable, var y=0 declares y and sets y to zero

    • sum = sum + z keeps a running total inside a loop

    • count++ increments a counter inside a loop

Practice

    1. Job 31: Calculate the sum and average of 1000 random numbers between 50 and 125.

    2. Job 32: You can set the contents of an array like this: saying[2] = "The early bird always gets the worm."; Create a web page that displays a different saying or proverb (from a list of 10) every time it is opened.

    3. NOTE: You can add HTML tags to change the text properties. "<H2>The early bird always gets the worm.</H2>" changes the size of the text to Heading 2 size.