10.19
Random学习,发现一个很有趣的网站http://programmingbydoing.com/,主要是觉得程序后面的问题,很有利于刚开始学习的我有帮助,所以记录下来。
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." ); } } }
后面的几个问题,觉得很有趣就都试了一下,
1.Delete the 1 +
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.
结果试了几次,发现原来RANDOM是从0开始到N-1的
2.Change the 1 +
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?
试了几次发现这种表达式只是在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?
我运行了几次之后发现,每次都结果都是一样的。查了API文件里面是这样写的:
使用SEED种子产生随机数,产生的数据会被保持。
方法是:
4.Change to random seed to something else and observe the behavior. What happens to the random numbers?
还是保持不变,但我把种子改成了3456,随机数据与种子是12345时不同了,应该是上面setSeed方法导致的。
最后是找到的在线文档,方便学习:http://tool.oschina.net/apidocs/apidoc?api=jdk_7u4
原文:http://www.cnblogs.com/missTS/p/4892807.html