JSP學習筆記(六十三):java中生成隨機數

weixin_34219944發表於2008-10-08

1.生成0~9之間的隨機數

    public static void main(String[] args) {
Random rnd
= new Random();
System.out.println(rnd.nextInt(
10));
}

 

2.生成1~9之間的隨機數

    public static void main(String[] args) {
Random rnd
= new Random();
System.out.println(rnd.nextInt(
9) + 1);

}

 

3.生成1~9之間不重複的隨機數

    public static void main(String[] args) {
int [] seed = {1,2,3,4,5,6,7,8,9};
int [] ranArr = new int [9];
Random ran
= new Random();
for(int i = 0 ; i<seed.length ; i++){
int j = ran.nextInt(seed.length-i);
ranArr [i]
= seed [j];
seed [j]
= seed [seed.length-1-i];
System.out.println (
"ranArr[" + i + "]" + ":" + ranArr[i]);
}
}

或者

    public static void main(String[] args) {
List
<Integer> list = new ArrayList<Integer>();

for(int i = 1; i <= 9; i++){
list.add(i);
}

Collections.shuffle(list);

for(Integer i : list){
System.out.println(i);
}
}

相關文章