Java获取指定范围随机数-Math.random()
公式:Math.random()*(n+1-m)+m,旨在返回[m,n]之间的随机数。
以下为两个实例应用。
- 获取2至20间的随机100个整数。
@Test
public void test3(){
for(int i = 0; i < 100 ; i++){
int value = (int) (Math.random()*(20+1-2) + 2);
System.out.println(value);
}
}
输出结果为:
2. 生成一个50位的随机a~z字符串。
public void test4(){
String result = "";
char chValue ;
int inValue;
for(int i = 0 ; i < 50; i++){
inValue = (int) (Math.random()*(122-97+1)+97);
chValue = (char) inValue;
result += chValue + " ";
}
System.out.println("运行结果:" + result);
}
运行结果: