1.Random:生成隨機(jī)數(shù)字的類
? ? ? ? 導(dǎo)包:import? ? java.util.Random;
? ? ? ? 創(chuàng)建:Random? ? r = new? ? Random();
? ??????使用:
? ??????????????????1.獲取隨機(jī)的Int數(shù)字(范圍是int所有范圍),如:int? ? num = r.nextInt();
? ? ? ? ? ? ? ? ? ? 2.獲取隨機(jī)的Int數(shù)字(參數(shù)代表范圍,左閉右開區(qū)間),如:int? ? num = r.nextInt(3);
? ? ? ? ? ? ? ? ? ? ? ? 取值范圍為0~2,取不到3的值。
代碼示例:取1~10范圍的值
import java.util.Random;
public class Random01 {
public static void main(String[] args) {
????????int num =10;
? ? ? ? int range =10;
? ? ? ? int result;
? ? ? ? Random r =new Random();
? ? ? ? for (int i =0; i < num; i++) {
????????????//執(zhí)行十次循環(huán)賦值輸出
????????????//本來范圍是[0,n),現(xiàn)在整體+1,范圍變成[1,n+1),即范圍是[1,n]
? ? ? ? ? ? result = r.nextInt(range) +1;? ? //生成1-10的隨機(jī)數(shù)
? ? ? ? ? ? System.out.println("隨機(jī)數(shù)是:" + result);
? ? ? ? }
????}
}
