0

I created this method randomInt, that gives a random number, between -5, and 15. I created another method randomIntArray that calls randomInt, in a loop, and stores the random integers into an array. However, when I try to print it, it just returns an ArrayIndexOutOfBoundsException.

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

public static int[] randomIntArray(int n) {
    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;
}

In randomInt, When I didn't cast the return value into an int, it worked, however I need it to return an int for the array to work.

Turing85
  • 18,217
  • 7
  • 33
  • 58
theUser
  • 91
  • 5
  • Can you show us the code where you print the array out and give us the stack trace.. – user2494817 Apr 15 '15 at 19:33
  • I do not believe that the code shown will produce an `OutOfBoundsException`. There must be a bug in the code to print the contents of the array, which you have not shown. Please add that code to the question. :-) – Jonathan Gilbert Apr 15 '15 at 19:35
  • The problem is probably in your printing routine. Try using `System.out.println(Arrays.toString(randomIntArray(n)))` to print and see if you still get the error. – Anderson Vieira Apr 15 '15 at 19:39

2 Answers2

2

Check your printing code after calling randomIntArray(number);

/**
 * @param args the command line arguments
 */
public static void main(String[]args) {
    int[] myArray = randomIntArray(10);

    // Manual iteration through your array
    for (int i = 0; i < myArray.length; i++) {
        System.out.print(myArray[i] + " ");
    }
    System.out.println("");

    // Use of Arrays class to print your array
    System.out.println(Arrays.toString(myArray));
} 

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

public static int[] randomIntArray(int n) {
    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;
}

Results:

enter image description here

Shar1er80
  • 9,001
  • 2
  • 20
  • 29
0

http://ideone.com/3OrTei

In the function calling randomIntArray(int n):

int[] array = randomIntArray(5);
for(int i = 0; i < array.length; i++)
{
    System.out.println(array[i]);
}

The code works, just make sure you're printing the results properly

Question Marks
  • 176
  • 1
  • 9
  • 17