1

So, I did re did the e=(high-low)*x+low, however, when I try to use it, it just returns an outOfBounds exception. When I didn't cast it into an int, it worked, however I ned it to return an integer, for the array to work.

public static int randomInt(int low, int high)
    {double e;
    double x=Math.random();
        e=(high-low)*x+low;
    return (int)e;}

Here is the method that calls the "randomInt" method

public static int[] randomIntArray(int n)//generates an array of random numbers based on an upper and lower bound
    {int[] a=new int[n];
    for(int i=0;i<a.length;i++)
        {a[i]=randomInt(-5,15);}//"-5&15 are the lower and upper bounds of the random number array
    return a;}
theUser
  • 91
  • 5

3 Answers3

7

x is between 0 and 1.

In order for e to be between low and high, you need:

e=(high-low)*x+low;
Jordi Castilla
  • 26,609
  • 8
  • 70
  • 109
Eran
  • 387,369
  • 54
  • 702
  • 768
2

Check this

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;
}
Community
  • 1
  • 1
Jordi Castilla
  • 26,609
  • 8
  • 70
  • 109
0

Use return (int) (Math.random()*(high-low)+low); as your function body instead.

user4759923
  • 531
  • 3
  • 12