This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
                                
                                    (25个答案)
                                
                        
                3年前关闭。
            
        

我创建了此方法randomInt,该方法给出了介于-5和15之间的随机数。我创建了另一个方法randomIntArray,该方法在循环中调用randomInt,并将随机整数存储到数组中。但是,当我尝试打印它时,它只返回一个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;
}


randomInt中,当我没有将返回值转换为int时,它可以工作,但是我需要它返回int才能使数组工作。

最佳答案

调用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;
}


结果:

07-28 13:54