整数数组不会打印

时间:2015-04-15 19:30:40

标签: java arrays prng

我创建了这个方法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才能使数组生效。

2 个答案:

答案 0 :(得分:2)

调用randomIntArray(数字)后检查您的打印代码;

/**
 * @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;
}

结果:

enter image description here

答案 1 :(得分:0)

http://ideone.com/3OrTei

在调用randomIntArray(int n)的函数中:

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

代码有效,只需确保正确打印结果