Java Reference
In-Depth Information
In Java, we can work with random numbers using the predefined static function random in the Math class;
random produces random fractions ( ³ 0.0 and < 1.0). We use it by writing Math.random() .
In practice, we hardly ever use random in the form provided. This is because, most times, we need random
numbers in a specific range (like 1 to 6 , say) rather than random fractions. However, we can easily write a function that
uses random to provide random integers from m to n where m < n . Here it is:
public static int random(int m, int n) {
//returns a random integer from m to n, inclusive
return (int) (Math.random() * (n - m + 1)) + m;
}
For example, the call random(1, 6) will return a random integer from 1 to 6, inclusive. If m = 1 and n = 6, then
n-m+1 is 6. When 6 is multiplied by a fraction from 0.0 to 0.999..., we get a number from 0.0 to 5.999.... When cast with
(int) , we get a random integer from 0 to 5. Adding 1 gives a random integer from 1 to 6.
As another example, suppose m = 5 and n = 20 . There are 20 - 5 + 1 = 16 numbers in the range 5 to 20 . When 16 is
multiplied by a fraction from 0.0 to 0.999..., we get a number from 0.0 to 15.999....When cast with (int) , we get a
random integer from 0 to 15. Adding 5 gives a random integer from 5 to 20.
Program P6.1 will generate and print 20 random numbers from 1 to 6. Each call to random produces the next
number in the sequence. Note that the sequence may be different on another computer or on the same computer
using a different compiler or run at a different time.
Program P6.1
import java.io.*;
public class RandomTest {
public static void main(String[] args) throws IOException {
for (int j = 1; j <= 20; j++) System.out.printf("%2d", random(1, 6));
System.out.printf("\n");
} //end main
public static int random(int m, int n) {
//returns a random integer from m to n, inclusive
return (int) (Math.random() * (n - m + 1)) + m;
} //end random
} //end class RandomTest
When run, Program P6.1 printed the following sequence of numbers:
4 1 5 1 3 3 1 3 1 3 6 2 3 6 5 1 3 1 1 1
When run a second time, it printed this sequence:
6 3 5 6 6 5 6 3 5 1 5 2 4 1 4 1 1 5 5 5
Each time it is run, a different sequence would be generated.
Search WWH ::




Custom Search