「随机在一个数组java」随机从数组中取一个元素
今天给各位分享随机在一个数组java的知识,其中也会对随机从数组中取一个元素进行解释,如果能碰巧解决你现在面临的问题,别忘了关注本站,现在开始吧!
本文目录一览:
java怎么生成1个随机数组
可以用Math.random()实现,生成X到X之间的一个数组;
参考代码如下:
Random random=new Random();
int [] r=new int[7];
for (int i = 0; i r.length;) {
int temp=random.nextInt(36);
if(temp==0)continue;
for (int j : r) {
if(j==temp)continue;
}
r[i]=temp;
i++;
}
java随机出来一个数组里边元素不重复的数组,要求数组长度6.元素在1~~33之间。
int a[33];
for(int i=0; ia.length; i++) {
a[i] = i + 1;
}
Random rand = new Random()
for(int n=0; n5000; n++) {
int i = rand.nextInt(33);
int j = rand.nextInt(33);
if(i != j) {
int t = a[i];
a[i] = a[j];
a[j] = t;
}
}
int b[6];
for(int i=0; ib.length; i++) {
b[i] = a[i];
}
java中如何将随机数放到数组里?
首先:java的Math类提供了一个
random()静态方法,返回带正号的
double
值,该值大于等于
0.0
且小于 1.0。返回值是一个伪随机选择的数,在该范围内(近似)均匀分布。
以下为范例:
//代码如下:
public class Test24 {
/*
* 随机从 1~10 取十个整数,存入数组
*/
public static void main(String[] args) {
int [] arr = new int[10]; //构建一个空的一维数组
for(int i=0;iarr.length;i++){
int temp = (int)(Math.random()*10)+1;//随机产生一个 1~10 的整数
arr[i] = temp;//将产生的数添加到数组
System.out.print(arr[i]+" ");
}
}
}
关于随机在一个数组java和随机从数组中取一个元素的介绍到此就结束了,不知道你从中找到你需要的信息了吗 ?如果你还想了解更多这方面的信息,记得收藏关注本站。