JSP学习笔记(六十三):java中生成随机数
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);
}
}