0

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.

1

2 Answers 2

1

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)];
Sign up to request clarification or add additional context in comments.

2 Comments

Hi Thorsten, thanks for your post, I tried args[i*x+j], it works, but how did u come up with this design? Is is about algorithm or logic math?
Well, it is pretty obvious if you think about it :-) Also, it is well known to anyone who has ever tried to access the pixels of an image from the underlying byte buffer.
0

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]>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.