Java Math: Random Numbers
If you every need to generate a random number, the Java Math class has that covered too. You might be working on a program that generates lottery numbers or perhaps one that picks random names from a hat. The random() method will return a double number between 0.0 and 1.0. That might seems like a narrow scope but since they are numbers we can multiple these random numbers to accommodate a wider range. The general syntax is:
Math.random()
Let’s see how we might return a random number and them apply multiplication to increase it’s range in Java:
//Generate a random number between 0.0 and 1.0 System.out.println(Math.random()); //Generate a random number between 0.0 and 100.0 System.out.println(Math.random()*101);
The output should be both rounded down values:
run: 0.8113503180366052 46.21010993425736 BUILD SUCCESSFUL (total time: 0 seconds)
Are the outputs what you expected? The first random number is between 00. and 1.0 and the second is between 0.0 and 100.0 so it looks correct. But as you can see, since the random() method returns a double, there are a lot of numbers after the decimal point. How might we change this so that we only have a whole number outputted?
Since Math.random() returns a double we are going to have up to 16 digits after the decimal point. If we want to remove all of these digits to leave a whole number how about we change the datatype to something that does not have a decimal point? The int datatype might work! Check the Java Datatypes and Variables lesson if you are unsure.
Next, we will need to convert that datatype of the returned random number from a double to an int. If you are unsure about how to do this you should check the lesson Java Datatype Conversion to remind yourself how to convert datatypes one one type to another.
Another important thing to remember is the operator processing order that is used in Java. This is the sequence that Java will execute operations like addition and multiplication, and how you can group operations using parenthesis, check the Java Operators lesson for a reminder.
[java]//Generate a random number between 0 and 100
System.out.println((int)(Math.random()*101));[/java]
Type this code into your IDE, the output should be something like:
run: 28 BUILD SUCCESSFUL (total time: 0 seconds)
This looks good! It is a whole number with no fractional part (and integer) and it will return a number between 0 and 100.