如何在Java中生成大随机数?
对于较大的随机数,请在Java中使用BigInteger类型。首先,创建一个Random对象-
Random randNum = new Random();
现在,声明一个字节数组并生成随机字节-
byte[] b = new byte[max];randNum.nextBytes(b);
现在,生成一个BigInteger类型的大随机数-
BigInteger bigInt = new BigInteger(b);
示例
import java.math.BigInteger;import java.util.Random;
public class Demo {
public static void main(String... a) {
int max = 10;
Random randNum = new Random();
byte[] b = new byte[max];
randNum.nextBytes(b);
//BigInteger类型
BigInteger bigInt = new BigInteger(b);
System.out.println("Very large random number = "+bigInt);
}
}
输出结果
Very large random number = 283258678185163472552410
以上是 如何在Java中生成大随机数? 的全部内容, 来源链接: utcz.com/z/350320.html