I am declaring a 2D array with column size as zero.while taking the input i am getting array index out of bound exception. I don't understand why?
我正在声明一个列大小为零的2D数组。在获取输入时,我得到数组索引超出绑定异常。我不明白为什么?
Scanner s=new Scanner(System.in);
int arr[][]=new int[3][0];
for(int i=0;i<3;i++)
{
for(int j=0;j<1;j++)
{
arr[i][j]=s.nextInt();
}
}
3 个解决方案
#1
1
Please try with:
请尝试:
int arr[][]=new int[3][1];
If you want an array of length one, you should declare it as:
如果你想要一个长度为1的数组,你应该将它声明为:
new int[1];
This would create an array that can hold one element, at index 0.
这将创建一个可以在索引0处保存一个元素的数组。
#2
0
Your code makes use of 0th column so you need to declare one column in the declaration
您的代码使用第0列,因此您需要在声明中声明一列
int[][] arr = new int[3][1];
#3
0
change j<1 to j<0 `
将j <1改为j <0`
for(int j=0;j<0;j++)
{
arr[i][j]=s.nextInt();
}
#1
1
Please try with:
请尝试:
int arr[][]=new int[3][1];
If you want an array of length one, you should declare it as:
如果你想要一个长度为1的数组,你应该将它声明为:
new int[1];
This would create an array that can hold one element, at index 0.
这将创建一个可以在索引0处保存一个元素的数组。
#2
0
Your code makes use of 0th column so you need to declare one column in the declaration
您的代码使用第0列,因此您需要在声明中声明一列
int[][] arr = new int[3][1];
#3
0
change j<1 to j<0 `
将j <1改为j <0`
for(int j=0;j<0;j++)
{
arr[i][j]=s.nextInt();
}