-1

I am beginner in java i want to take input of an multidimensional array from user using for loop.

i have tried the following code but its giving some thread error.

Scanner input = new Scanner(System.in);
for(i=0;i<2;i++)
{
    for(j=0;j<2;j++)
    {
        a[i][j] = input.nextInt();
        //System.out.println(a[i][j]);
    }
}
}

Scanner input = new Scanner(System.in);
for(i=0;i<2;i++)
{
    for(j=0;j<2;j++)
    {
        int a[i][j] = input.nextInt();
        }
}
}

Exception in thread "main" java.lang.NullPointerException at practice.prac.main(prac.java:16)

3 Answers3

0

You can do something like this:

Scanner sc = new Scanner(System.in);
System.out.print("Input total row : ");
int row = sc.nextInt();
System.out.print("Input total column : ");
int column = sc.nextInt();

int [][] matrix = new int[row][column];
Khaled Jamal
  • 628
  • 1
  • 6
  • 18
0
int i,j,a[][] = new int[2][2];

Scanner input = new Scanner(System.in);

for(i=0;i<2;i++)
{
    for(j=0;j<2;j++)
    {
        a[i][j] = input.nextInt();
        }
}
for(i=0;i<2;i++)
{
    System.out.print("\n");
    for(j=0;j<2;j++)
    {
        System.out.print(a[i][j] + "\t");
    }
}
}
0

An Array needs to be initialized before used. Because an array has fixed size this could be done like this:

int[][] a = new int[2][2];

After that your first loop seems to be ok

Scanner input = new Scanner(System.in);
for(i=0;i<2;i++)
{
    for(j=0;j<2;j++)
    {
        a[i][j] = input.nextInt();
        //System.out.println(a[i][j]);
    }
}
}

And if you want to do it correct you do it like this.

Scanner input = new Scanner(System.in);
    for (int i = 0; i < a.length; i++) {
        for (int j = 0; j < a[i].length; j++) {
            a[i][j] = input.nextInt();
        }
    }
    input.close();

    for (int i = 0; i < a.length; i++) {
        for (int j = 0; j < a[i].length; j++) {
            System.out.print(a[i][j] + "\t");
        }
        System.out.println();
    }

That is wrong usage of arrays:

int a[i][j] = input.nextInt();