integer array won't print

95 Views Asked by At

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.

2

There are 2 best solutions below

0
Shar1er80 On

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

0
Question Marks On

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