pei wang
pei wang

Reputation: 295

Command line input for two D arrays in Java

I have a question regarding to how to use command line argument input for two dimensional array, please see the codes:

                 ...
            double[] a = new double[args.length];
            for (int i = 0; i < args.length; i++) {
             a[i] = Double.parseDouble(args[i]);
                } 
              ...

The above codes are the command line input for one dimensional array, the length and elements can be done with argument input, however, how to do the same way with two dimensional arrays? Thanks.

Upvotes: 0

Views: 4476

Answers (2)

dARKpRINCE
dARKpRINCE

Reputation: 1568

Command line arguments can only be one dimensional. But you could add parameters to specify the size of the 2 dimensional array and then input the array values. Like

<Dimension size m> <Dimension size n> <array value [0][0]> ... <array value [m][n]>

Upvotes: 0

Thorsten Dittmar
Thorsten Dittmar

Reputation: 56697

It really depends on what the dimensions of your array should be. One of them needs to be fixed for this to work the same as the code you've shown.

Example: If you assume that the second dimension of your array is x, the number of elements can be calculated as

int arrayLength = args.length / x;

You could then parse the parameters like this:

for (int i = 0; i < arrayLength; i++)
{
    for (int j = 0; j < x; j++)
    {
        a[i][j] = args[i * x + j];
    }
}

The other, more flexible way would be to specify the dimensions in the first two parameters and then use the following code

int dim1 = (int)args[0];
int dim2 = (int)args[1];

for (int i = 0; i < dim1; i++)
   for (int j = 0; j < dim2; j++)
       a[i][j] = args[2 + (i * dim1 + j)];

Upvotes: 1

Related Questions