如何生成随机数
对于如何生成随机数一般有以下几个方法
1.直接调用Math.random()函数
int x=(int)(Math.random()*6)——生成0-5的随机数
import javax.swing.JOptionPane; public class RandomInt { public static void main( String args[] ) { int value; String output = ""; for ( int i = 1; i <= 20; i++ ) { value = 1 + (int) ( Math.random() * 6 ); output += value + " "; if ( i % 5 == 0 ) output += "\n"; } JOptionPane.showMessageDialog( null, output, "20 Random Numbers from 1 to 6", JOptionPane.INFORMATION_MESSAGE ); System.exit( 0 ); } }
2.JDK提供了Random类
import java.util.Random
Random r=new Random();
int x=r.nextInt(100)+1生成一个1到101的随机数
import java.util.*; public class TestRandom { public static void main(String[] args) { Random rand = new Random(); System.out.println("rand.nextBoolean():" + rand.nextBoolean()); byte[] buffer = new byte[16]; rand.nextBytes(buffer); System.out.println(Arrays.toString(buffer)); //生成0.0~1.0之间的伪随机double数 System.out.println("rand.nextDouble():" + rand.nextDouble()); //生成0.0~1.0之间的伪随机float数 System.out.println("rand.nextFloat():" + rand.nextFloat()); //生成平均值是 0.0,标准差是 1.0的伪高斯数 System.out.println("rand.nextGaussian():" + rand.nextGaussian()); //生成一个处于long整数取值范围的伪随机整数 System.out.println("rand.nextInt():" + rand.nextInt()); //生成0~26之间的伪随机整数 System.out.println("rand.nextInt(26):" + rand.nextInt(26)); //生成一个处于long整数取值范围的伪随机整数 System.out.println("rand.nextLong():" + rand.nextLong()); } }
3.带种子的随机数
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 r4 = new Random(System.currentTimeMillis());