close

java.util.Random這個類別是專門用來產生亂數的。

import java.util.Random;
public class Test {
public static void main(String[] args) {
Random random = new Random();
for (int i = 0; i System.out.print(random.nextInt(10) + " ");
}
}
}



random.nextInt(10)可以產生0~9之間的整數亂數。
除了netInt的方法外,還有nextLong、nextDouble
、nextBoolean、nextByte等方法可用...API都有寫。

Math.random(),則是Math類別裡產生亂數的靜態方法,
它可以產生0.0~0.1之間的亂數。
1 + (int) (Math.random()*100)



例如這行Code則是可以產生1~100之間的整數亂數。

arrow
arrow
    全站熱搜
    創作者介紹
    創作者 lupohsunrock 的頭像
    lupohsunrock

    lupohsunrock的部落格

    lupohsunrock 發表在 痞客邦 留言(0) 人氣()