'How to take 2D array inputs from command Line arguments in java?

I have to take inputs from the command line and assign them to a 2X2 array.

Input = 1 2 3 4 (from cmd line)
output = 1 2 
         3 4


  int a[][] = new int[2][2];
        // taking 2D array inputof size 2X2 from cmdline
        for(int i=0;i<a.length;i++){
            for(int j=0;j<a[i].length;j++){
                int n = Integer.parseInt(args[i]);
                a[i][j] = n;
          }
        }
        for(int i=0;i<args.length;i++){
            for(int j=0;j<a[0].length;j++){
                System.out.print(a[i][j]+" ");
          }
       }

But Getting output as:

1 1 
2 2 


Solution 1:[1]

You could do something like

public static void main(String[] args)
{
    int a[][] = new int[2][2];

    for(int i=0; i<2; ++i)
    {
        for(int j=0; j<2; ++j)
        {
            a[i][j]=Integer.parseInt(args[2*i+j]);
        }
    }
}

where the command line arguments will get stored in the array args. The strings are converted to numbers using parseInt().

The 2*i+j is used to get the appropriate index to the args array.

Proper exception handling should also be added to this.

Print the result like

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

Solution 2:[2]

class Demo
{
    public static void main(String[] args)
    {
        int a[][] = new int[3][3];
        int i,j;
        for( i=0; i<3; ++i)
        {
            for( j=0; j<3; ++j)
            {
                a[i][j]=Integer.parseInt(args[3*i+j]);
            }
        }

        for( i=0; i<3; ++i)
        {
            for(j=0; j<3; ++j)
            {
                System.out.println(a[i][j]+" ");
            }
        }
    }
}

Solution 3:[3]

public static void main(String[] args)
{
    int a[][] = new int[2][2];

    for(int i=0; i<2; ++i)
    {
        for(int j=0; j<2; ++j)
        {
            a[i][j]=Integer.parseInt(args[2*i+j]);
        }
    }
    //for print
    for(int i=0; i<2; ++i)
    {
         for(int j=0; j<2; ++j)
         { 
              System.out.print(a[i][j]+" ");
         }
         System.out.println();
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 J...S
Solution 2 Viij
Solution 3 shubham kumar saurabh