jsp:如何实现从现有的数据中随机取出其中的几个数据?

来源:百度知道 编辑:UC知道 时间:2024/05/17 14:07:08
例如:现有数据为:39 45 26 76 90 23 10 怎样实现从中随机取出3个数?
各位麻烦请用java语言写代码,谢谢!!

public class Test {
public static void main(String[] args) {
int[] n = { 39, 45, 26, 76, 90, 23, 10 };
int len=n.length;
for (int j = 0; j < 3; j++) {
int i = (int) (Math.random() * len);
System.out.println(n[i]);
n[i]=n[len-1];
len--;
}
}
}

先把数据库中的数字取出来,
装在数组中,然后采用随机数,选取数组中的值。

public static void main(String[] args) {
int[] arr= {39,45,26,76,90,23,10 };
Random random = new Random();
for(int i=0; i<3; i++){
System.out.println(arr[random.nextInt(arr.length)]);
}
}

}