如何在 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 type BigInteger bigInt = new BigInteger(b); System.out.println("Very large random number = "+bigInt); } }
輸出
Very large random number = 283258678185163472552410
廣告