Random learning, random
10.19
Random learning and discovering a very interesting website.
import java.util.Random;public class Randomness{ public static void main ( String[] args ) { Random r = new Random(); int x = 1 + r.nextInt(10); System.out.println( "My random number is " + x ); System.out.println( "Here are some numbers from 1 to 5!" ); System.out.print( 1 + r.nextInt(5) + " " ); System.out.print( 1 + r.nextInt(5) + " " ); System.out.print( 1 + r.nextInt(5) + " " ); System.out.print( 1 + r.nextInt(5) + " " ); System.out.print( 1 + r.nextInt(5) + " " ); System.out.print( 1 + r.nextInt(5) + " " ); System.out.println(); System.out.println( "Here are some numbers from 1 to 100!" ); System.out.print( 1 + r.nextInt(100) + "\t" ); System.out.print( 1 + r.nextInt(100) + "\t" ); System.out.print( 1 + r.nextInt(100) + "\t" ); System.out.print( 1 + r.nextInt(100) + "\t" ); System.out.print( 1 + r.nextInt(100) + "\t" ); System.out.print( 1 + r.nextInt(100) + "\t" ); System.out.println(); int num1 = 1 + r.nextInt(10); int num2 = 1 + r.nextInt(10); if ( num1 == num2 ) { System.out.println( "The random numbers were the same! Weird." ); } if ( num1 != num2 ) { System.out.println( "The random numbers were different! Not too surprising, actually." ); } }}
I tried the following questions if I found them interesting,
1. Delete1 +
In front of all six lines that pick numbers 1-5, so that they look like this:System.out.print( r.nextInt(5) + " " );
Run the program a few times, and see if you can figure out what range the new random numbers are in.
The result is tried several times and it is found that the original RANDOM is from 0 to the N-1
2. Change1 +
In front of all six lines that pick numbers 1-5, so that they look like this:System.out.print( 3 + r.nextInt(5) + " " );
Run the program a few times. Is it picking random numbers from 3 to 5? If not, what range are they?
I tried several times and found that this expression only adds a definite value in the RANDOM.
3. Change the line where you create the random number generator so that it looks like this:Random r = new Random(12353);
This number is called a seed. Run the program a few times. What do you notice? What happened to the random numbers?
After running it several times, I found that the results are the same every time. The following code is written in the API file:
When a random number is generated using the SEED, the generated data is maintained.
The method is:
4. Change to random seed to something else and observe the behavior. What happens to the random numbers?
It remains unchanged, but I changed the seed to 3456. the random data is different from the seed to 12345. It should be caused by the setSeed method above.
Finally is to find the online documentation for easy learning: http://tool.oschina.net/apidocs/apidoc? Api = jdk_7u4