Java 为什么我的代码会导致ArrayIndexOutOfBoundsException?
我试图创建一个程序,根据用户的输入创建一个数组,用户也输入最大和最小的数字。代码如下:Java 为什么我的代码会导致ArrayIndexOutOfBoundsException?,java,arrays,indexoutofboundsexception,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("Plea
//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]);
}
我一直在寻找答案,但没有找到任何答案,非常感谢您的帮助。此代码块包含错误
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;
要理解正在发生的事情,你需要知道
- 数组的长度为
arraylength
- 数组元素从0到
arraylength-1进行编号/索引
像
userArray[arraylength]
这样的调用会导致java.lang.ArrayIndexOutOfBoundsException
,因为您试图访问索引6处的元素,而允许的最高值是5。您认为userArray[arraylength]
中会发生什么?在[…]
中可以使用哪些值,在数组长度中存储哪些值?它告诉您数组索引大于可以在该数组上使用的最大索引。如果创建的数组大小为arrayLength
,则根据定义,arrayLength
将太大,无法作为该数组的索引。(我猜你的意思是说userArray[I]
,而不是userArray[arraylelength]
)
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]);
}
userArray[arraylength] = range;