Array index out of Bound exception for a 2d array

3743 views java
1

I am declaring a 2 d array with column size as zero.while taking the input i am getting array index out of bound exception.I don't understand why?

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();
    }
}

answered question

then what is the use of creating 2d array?

3 Answers

3

Please try with int arr[][]=new int[3][1];

If you want an array of length one, you should declare it as:

new int[1];

This would create an array that can hold one element, at index 0.

posted this
11

Your code makes use of 0th column so you need to declare one column in the declaration

int[][] arr = new int[3][1];

posted this
5

change j<1 to j<0 `

for(int j=0;j<0;j++)
{
    arr[i][j]=s.nextInt();
}

posted this

Have an answer?

JD

Please login first before posting an answer.