Java随机数有多种获取方法,比如使用Math.random()(它可以获得[ 0,1)之间的一个随机数)
代码:
import javax.swing.*;
public class RollDie {
public static void main( String args[] )
{
int frequency1 = 0, frequency2 = 0,
frequency3 = 0, frequency4 = 0,
frequency5 = 0, frequency6 = 0, face;
// summarize results
for ( int roll = 1; roll <= 6000; roll++ ) {
face = 1 + (int) ( Math.random() * 6 );
switch ( face ) {
case 1:
++frequency1;
break;
case 2:
++frequency2;
break;
case 3:
++frequency3;
break;
case 4:
++frequency4;
break;
case 5:
++frequency5;
break;
case 6:
++frequency6;
break;
}
}
JTextArea outputArea = new JTextArea( 7, 10 );
outputArea.setText(
"Face\tFrequency" +
"\n1\t" + frequency1 +
"\n2\t" + frequency2 +
"\n3\t" + frequency3 +
"\n4\t" + frequency4 +
"\n5\t" + frequency5 +
"\n6\t" + frequency6 );
JOptionPane.showMessageDialog( null, outputArea,
"Rolling a Die 6000 Times",
JOptionPane.INFORMATION_MESSAGE );
System.exit( 0 );
}
}
运行截图:
也可以通过Random类获得随机数,代码如下:
import java.util.Random;
public class TestSeed
{
public static void main(String[] args)
{
Random r1 = new Random(50);
System.out.println("第一个种子为50的Random对象");
System.out.println("r1.nextBoolean():\t" + r1.nextBoolean());
System.out.println("r1.nextInt():\t\t" + r1.nextInt());
System.out.println("r1.nextDouble():\t" + r1.nextDouble());
System.out.println("r1.nextGaussian():\t" + r1.nextGaussian());
System.out.println("---------------------------");
Random r2 = new Random(50);
System.out.println("第二个种子为50的Random对象");
System.out.println("r2.nextBoolean():\t" + r2.nextBoolean());
System.out.println("r2.nextInt():\t\t" + r2.nextInt());
System.out.println("r2.nextDouble():\t" + r2.nextDouble());
System.out.println("r2.nextGaussian():\t" + r2.nextGaussian());
System.out.println("---------------------------");
Random r3 = new Random(100);
System.out.println("种子为100的Random对象");
System.out.println("r3.nextBoolean():\t" + r3.nextBoolean());
System.out.println("r3.nextInt():\t\t" + r3.nextInt());
System.out.println("r3.nextDouble():\t" + r3.nextDouble());
System.out.println("r3.nextGaussian():\t" + r3.nextGaussian());
Random r4 = new Random(System.currentTimeMillis());
System.out.println("以当前时间为种子的Random对象");
System.out.println("r3.nextBoolean():\t" + r4.nextBoolean());
System.out.println("r3.nextInt():\t\t" + r4.nextInt());
System.out.println("r3.nextDouble():\t" + r4.nextDouble());
System.out.println("r3.nextGaussian():\t" + r4.nextGaussian());
}
}
运行结果如下:(以当前时间为种子的Random对象时,输出部分r3忘记改成r4了)
相同的“种子”会生成相同的随机数,但是将当前时间为种子的Random对象后就在很大成都上解决了这个问题。
关于Java中方法重载的相关实例在前面的博客已经发表过一次了,此处就不再重复。
递归方法是编程语言中一种化繁为简的思想,不过它在简化空间复杂度的同时增加了时间复杂度,当递归次数太多时计算机会出现“罢工”现象。
标签:Java,语言,r3,Random,System,r1,println,程序设计,out From: https://www.cnblogs.com/yansans/p/16814575.html