Java Random Integers

This code assigns x a random int number from 0 to 9:

x = (int)(Math.random()*10);

Math.random() creates a random decimal number (double) from 0 to 1, not including 1.

Multiplying by 10 gives a decimal from 0 to almost 10, always less than 10.

Adding “(int)” at the beginning will type cast the number to an integer, which will remove the decimal places and round it down to a whole number. Now the number is an int from 0 to 9.

In order for this to work correctly, you need parentheses around Math.random()*10 as shown above. If you leave those parentheses out, the random number from 0 to almost 1 is type cast to an int before it’s multiplied by 10, so that will always equal zero. Then it will still be zero after you multiply by 10.

Change the 10 to a different number to get a different range of numbers.

Add one if you want 1 to 10 instead of 0 to 9.