java用Random类、Math类产生一组10~50之间随机数
程序员文章站
2024-03-19 10:55:52
...
Math类下的random方法产生一个[0,1)的double浮点数;
Random类的nextInt(n)方法产生一个[0,n)的整数;
代码如下:
import java.util.*;
public class RandomTest{
public static void main(String[] args){
int ARRAYLENGTH = 10;
int a[] = new int[ARRAYLENGTH];
int b[] = new int[ARRAYLENGTH];
Random ran = new Random();
for(int i = 0; i < a.length; i++){
//Random类nextInt()方法产生随机数
a[i] = ran.nextInt(40) + 10;
//Math类random()方法产生随机数
b[i] = (int)(Math.random()*40) + 10;
}
System.out.println("数组a为:" + Arrays.toString(a));
System.out.println("数组b为:" + Arrays.toString(b));
}
}
输入为:
数组a为:[22, 17, 15, 42, 46, 27, 43, 33, 19, 37]
数组b为:[15, 38, 21, 41, 43, 42, 45, 31, 34, 34]