一:獲取隨機數的函數:
package test; import java.util.Random; /** * * @ClassName: NextIntDemo * @Description: nextInt()函數 * @author William_Dai * @date 2019年5月21日 * */ public class NextIntDemo { public static void main(String[] args) { //如果想得到30到200的(包含30和200)這個跨度的數在java中一般可以有如下方式獲得 //方法一: //int i = (int)(Math.random()*2) + 30; //[30,31] int i = (int)(Math.random()*171) + 30; ////[30,200] //方法二: Random r = new Random () ; //int j = r.nextInt (2) ; // [0,1] //int j = r.nextInt (201) ; // [0,200] int j = r.nextInt (171) + 30; // [30,200] //System.out.println("j:"+j); } }
二:構造一個數組並打印
package test; import java.util.Random; /** * * @ClassName: NextIntDemo * @Description: nextInt()函數 * @author William_Dai * @date 2019年5月21日 * */ public class NextIntDemo { public static void main(String args[]){ int[] array=creatArray(10); //構造數組 printArray(array); //以固定格式打印數組 } public static int[] creatArray(int length){ //構造含length個元素的數組的方法 int[] array =new int[length]; Random rad=new Random(); //產生隨機數的方法 for(int i=0;i<array.length;i++){ int value = rad.nextInt(100); //rad.nextInt(100) 意思是隨機產生一個大於等於0小於100的數 --即包含0不包含100 array[i]=value; } return array; } public static void printArray(int[] array){ //固定格式打印數組 for(int i=0;i<array.length;i++){ System.out.print(array[i]+"\t"); } } }
輸出結果: