[英]java.lang.ArrayIndexOutOfBoundsException when filling 2d array with user input
This is the code I have currentlly. 这是我目前拥有的代码。
public static void testClosestToMean() {
Scanner input = new Scanner(System.in);
System.out.println("How many rows does your array have: ");
int rows = input.nextInt();
System.out.println("How many columns does your array have: ");
int columns = input.nextInt();
double[][] numbers = new double[rows][columns];
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < columns; j++)
{
System.out.println("Enter a value for your array: ");
double values = input.nextDouble();
numbers[rows][columns] = values;
}
}
}
When I run my program I reach System.out.println("Enter a value for your array: ");
当我运行程序时,我到达
System.out.println("Enter a value for your array: ");
however when I input a single number and press enter this error occurs: 但是,当我输入一个数字并按Enter时,会发生此错误:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException
线程“主”中的异常java.lang.ArrayIndexOutOfBoundsException
I'm just generally stuck and would like guidance or even an explanation of why this error keeps occurring. 我只是被困住了,想要提供指导,甚至是为什么继续出现此错误的解释。
The indices of your 2D array run from 0
to row-1
for the rows and 0
to columns-1
for the columns. 2D数组的索引
row-1
从0
到row-1
,列的从0
到columns-1
。 However, you'r trying to access numbers[rows][columns]
which is known as an "off-by-one error" because your accessing indices that are each one more than the max possible index. 但是,您正在尝试访问
numbers[rows][columns]
,这被称为“一一失误”,因为您所访问的索引都比最大可能索引多一个。 If you want to fix this, then replace rows
with i
and columns
with j
like so, 如果要解决这个问题,然后更换
rows
与i
和columns
与j
像这样,
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < columns; j++)
{
System.out.println("Enter a value for your array: ");
double values = input.nextDouble();
numbers[i][j] = values;
}
}
This way, you're adding entries into your 2D array by filling each row starting from the first row (at index 0
) until you reach the last row (at index i-1
). 这样,您可以通过填充从第一行(索引为
0
)到最后一行(索引为i-1
)的每一行,将条目添加到2D数组中。 And while you're filling each row, you start filling the columns one by one by starting at the first column (at index 0
) until you reach the last column (at index j-1
). 在填充每一行时,您将从第一列(索引为
0
)开始,直到到达最后一列(索引为j-1
),开始逐一填充列。
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException
means you are exceeding the elements. 线程“主”中的异常
java.lang.ArrayIndexOutOfBoundsException
表示您超出了元素。 Please be aware that 0 can also be an item in an array. 请注意,0也可以是数组中的项目。
For example: 例如:
array[0] = "Hey";
array[1] = "Sup! wow... just wow";
If I did 如果我做了
system.out.println(array[2]);
It would print the error 它将显示错误
But if i did 但是如果我做到了
system.out.println(array[0], array[1]);
It would work. 会的。
In your code here : 在您的代码中:
numbers[rows][columns] = values;
I believe you meant 我相信你的意思
numbers[i][j] = values;
Thanks 谢谢
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.