Java 随机数不是';不受约束
因此,我重新执行了Java 随机数不是';不受约束,java,arrays,histogram,Java,Arrays,Histogram,因此,我重新执行了e=(high-low)*x+low,但是,当我尝试使用它时,它只返回一个outOfBounds异常。当我没有将它转换为int时,它工作了,但是我将它转换为返回一个整数,数组才能工作 public static int randomInt(int low, int high) {double e; double x=Math.random(); e=(high-low)*x+low; return (int)e;} 下面是调用“rand
e=(high-low)*x+low
,但是,当我尝试使用它时,它只返回一个outOfBounds异常。当我没有将它转换为int时,它工作了,但是我将它转换为返回一个整数,数组才能工作
public static int randomInt(int low, int high)
{double e;
double x=Math.random();
e=(high-low)*x+low;
return (int)e;}
下面是调用“randomInt”方法的方法
publicstatic int[]randomIntArray(int n)//根据上下限生成一个随机数数组
{int[]a=新的int[n];
对于(int)i=0;ix在0和1之间
为了使e介于低
和高
之间,您需要:
e=(high-low)*x+low;
x在0和1之间
为了使e介于低
和高
之间,您需要:
e=(high-low)*x+low;
检查
检查
使用return(int)(Math.random()*(high-low)+low);
作为函数体。使用return(int)(Math.random()*(high-low)+low)作为你的函数体。为什么不使用?这不应该抛出一个OutOfBoundsException。事实证明,OutOfBoundsException不是来自我必须打印的打印方法。为什么不使用?这不应该抛出OutOfBoundsException。事实证明,OutOfBoundsException是来自我的打印方法当我使用它的时候,我只得到一个越界异常当我使用它的时候,我只得到一个越界异常
public static int randInt(int min, int max) {
Random rand = new Random();
// nextInt is normally exclusive of the top value,
// so add 1 to make it inclusive
int randomNum = rand.nextInt((max - min) + 1) + min;
return randomNum;
}