为什么我的代码会导致ArrayIndexOutOfBoundsException?

时间:2014-10-05 18:40:20

标签: java arrays indexoutofboundsexception

我正在尝试创建一个程序,根据用户的输入创建一个数组,用户还可以输入最大和最小数字。这是代码:

//Ask the user to enter the length of the array
System.out.println("Please enter the length of the array: ");
int arraylength = input.nextInt();

//Ask the user to enter a max value
System.out.println("Please enter the max value: ");
int max = input.nextInt();

//Ask the user to input the min value
System.out.println("Please enter the min value: ");
int min = input.nextInt();

//Initialize the array based on the user's input
double [] userArray = new double[arraylength];


int range = (int)(Math.random() * max) + min;

/**
 *The program comes up with random numbers based on the length
 *entered by the user. The numbers are limited to being between
 *0.0 and 100.0
 */
for (int i = 0; i < userArray.length; i++) {
    //Give the array the value of the range
    userArray[arraylength] = range;
    //Output variables
    System.out.println(userArray[arraylength]);
}

问题似乎在于输入的数组长度,在这一行:

userArray[arraylength] = range;

我一直在寻找答案,但没有想出任何帮助,非常感谢任何帮助。

2 个答案:

答案 0 :(得分:2)

你是对的问题线。它是

userArray[arraylength] = range;

要了解正在发生的事情,您需要知道

  • 数组的长度为arraylength
  • 数组元素的编号/索引从0到arraylength-1

userArray[arraylength]之类的调用会导致java.lang.ArrayIndexOutOfBoundsException,因为您尝试访问索引为6的元素,而允许的最高值为5。

答案 1 :(得分:1)

此代码块包含错误;

for (int i = 0; i < userArray.length; i++) {
    //Give the array the value of the range
    userArray[arraylength] = range;
    //Output variables
    System.out.println(userArray[arraylength]);
}

您需要将arraylength更改为i

for (int i = 0; i < userArray.length; i++) {
    //Give the array the value of the range
    userArray[i] = range;
    //Output variables
    System.out.println(userArray[i]);
}