Random学习

王朝学院·作者佚名  2016-08-27
窄屏简体版  字體: 小  |  中  |  大  |  超大  

10.19

Random学习,发现一个很有趣的网站http://PRogrammingbydoing.com/,主要是觉得程序后面的问题,很有利于刚开始学习的我有帮助,所以记录下来。

importjava.util.Random;publicclassRandomness

{publicstaticvoidmain ( String[] args )

{

Random r=newRandom();intx = 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();intnum1 = 1 + r.nextInt(10);intnum2 = 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 the1 +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 the1 +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

 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
© 2005- 王朝網路 版權所有 導航