Java 產生隨機數主要有三條路:
1、Math.random():回傳 0 到 1 之間的 double 隨機值。
2、new Random():random.nextInt(100) 可取得 0 到 100 之間的 int 隨機值。
3、System.currentTimeMillis():回傳從 1970 年 1 月 1 日 0 時 0 分 0 秒到現在的毫秒數,型別為 long。
範例程式碼:
package com.njupt.acm;
import java.util.Random;
public class Test1 {
public static void main(String[] args) {
generateRandomNumber3();
}
public static void generateRandomNumber1() {
Random r = new Random();
for( int i = 0 ; i < 100 ; ++i ){
if(i % 10 == 0 && i != 0){//每 10 個換一行
System.out.println();
}
System.out.print(" "+ r.nextInt(100));// 產生 [0,100) 之間的數字
}
}
public static void generateRandomNumber2(){
for(int i = 0 ; i < 100 ; ++i ){
if( i % 10 ==0 && i != 0){
System.out.println();
}
System.out.print(Math.random() *100);// 0~100 之間的 double 隨機數
}
}
public static void generateRandomNumber3(){
//System.currentTimeMillis() 回傳 1970-01-01 00:00:00 到現在的毫秒數,型別 long
long nowTime = System.currentTimeMillis();
long tianshu = (nowTime/1000/60/60/24);
System.out.println("從 1970 年 1 月 1 日 0 點 0 分 0 秒到目前的毫秒數是:" + nowTime);
System.out.println("從 1970 年 1 月 1 日 0 點 0 分 0 秒到目前的年數是:" + (tianshu/365));
}
}