更新時間:2022-08-16 08:24:37 來源:動力節點 瀏覽6890次
相信大家對Java數組的定義已經有所了解,那么,Java生成隨機數組的方法有哪些?動力節點小編來告訴大家??梢栽?Java 中生成整數、浮點、雙精度、長整數和布爾類型的特定范圍內的隨機數。
要使用Random類生成隨機數,請按照以下步驟操作:
導入類java.util.Random
使類 Random 的實例,即 Random rand = new Random()
調用 rand 對象的以下方法之一:
nextInt(upperbound)生成 0 到 范圍內的隨機數upperbound-1。
nextFloat()生成一個介于 0.0 和 1.0 之間的浮點數。
nextDouble()生成介于 0.0 和 1.0 之間的雙精度數。
import java.util.Random;
class GenerateRandom {
public static void main( String args[] ) {
Random rand = new Random(); //instance of random class
int upperbound = 25;
//generate random values from 0-24
int int_random = rand.nextInt(upperbound);
double double_random=rand.nextDouble();
float float_random=rand.nextFloat();
System.out.println("Random integer value from 0 to" + (upperbound-1) + " : "+ int_random);
System.out.println("Random float value between 0.0 and 1.0 : "+float_random);
System.out.println("Random double value between 0.0 and 1.0 : "+double_random);
}
}
要使用 生成范圍內的隨機數Math.random(),請執行以下步驟:
聲明范圍的最小值
聲明范圍的最大值
使用公式Math.floor(Math.random()*(max-min+1)+min)生成包含min和 的max值。
class GenerateRandom {
public static void main( String args[] ) {
int min = 50;
int max = 100;
//Generate random int value from 50 to 100
System.out.println("Random value in int from "+min+" to "+max+ ":");
int random_int = (int)Math.floor(Math.random()*(max-min+1)+min);
System.out.println(random_int);
}
}
要使用類生成隨機數ThreadLocalRandom,請按照以下步驟操作:
導入類 java.util.concurrent.ThreadLocalRandom
調用方法
生成 int 類型的隨機數ThreadLocalRandom.current().nextInt()
生成雙精度類型的隨機數ThreadLocalRandom.current().nextDouble()
生成布爾類型的隨機數ThreadLocalRandom.current().nextBoolean()
import java.util.concurrent.ThreadLocalRandom;
class GenerateRandom {
public static void main( String args[] ) {
// Generate random integers
int int_random = ThreadLocalRandom.current().nextInt();
// Print random integers
System.out.println("Random Integers: " + int_random);
// Generate Random doubles
double double_rand = ThreadLocalRandom.current().nextDouble();
// Print random doubles
System.out.println("Random Doubles: " + double_rand);
// Generate random booleans
boolean boolean_rand = ThreadLocalRandom.current().nextBoolean();
// Print random booleans
System.out.println("Random Booleans: " + boolean_rand);
}
}
以上就是關于“Java生成隨機數組的方法”介紹,大家如果想了解更多相關知識,可以關注一下動力節點的Java基礎教程,里面的課程內容細致全面,很適合沒有基礎的小伙伴學習,希望對大家能夠有所幫助。
0基礎 0學費 15天面授
有基礎 直達就業
業余時間 高薪轉行
工作1~3年,加薪神器
工作3~5年,晉升架構
提交申請后,顧問老師會電話與您溝通安排學習