问题
今天想让程序返回一个区间内的随机数。忘记怎么写了,就去百度搜给出的结果并不对。
import java.util.Random;
/**
* @author HP
* @date 2019/4/16
*/
public class randomTest {
public static void main(String[] args) {
Random random = new Random();
//生成64-128内的随机数
int i = random.nextInt() * (128 - 64 + 1) + 64;
/**
* 生成 [m,n] 的数字
* int i1 = random.nextInt() * (n-m+1)+m;
* */
//生成0-64内的数字
int i1 = random.nextInt() * (64-0+1);
/**
* 生成0-n之内的数字
* int i1 = random.nextInt() * (n-0+1);
*
*
* */
}
}
这样是不对的,我就去查看API文档,发现nextInt()可以有参数也可以无参数。
无参数的方法直接调用返回的是一个很大的正负区间上的数。
如果想返回想要的范围内的数,应该:
package chapter6;
import java.util.Random;
import org.omg.Messaging.SyncScopeHelper;
public class RandomTest {
public static void main(String[] args) {
Random random = new Random();
for(int i=0;i<200;i++)
{
// 输出为0~13之间的整数
System.out.println(random.nextInt(14));
}
System.out.println("----------------------------");
for(int j=0;j<100;j++){
// 输出为-9~0之间的整数
System.out.println(random.nextInt(10)-9);
}
}
}