1

I have a function which has values in matrix form with String... array (var args in jdk 1.4) format. Can I add the values having 2D array and adding the values from the array in it.

Matrix m = new Matrix(3,3,
            "2",         "2",      "5 /",
            "3 3 *", "7",       "2",    
            "1 1 +",   "1 1 /", "3"
    );

And the function call :

public Matrix(int nRows, int nCols, String... exprArray) {

     Stack<String []> tks = new Stack<String []>();
     String arr[][] = null ;
    for(int i = 0; i < nRows; i++){
        for(int k = 0; k<nCols;k++){

         /****Add the value in 2D array using exprArray dont know how to do it can anyone help me out here *****/

        arr[i][k] = exprArray[i];
        System.out.println(arr[i][k]);

        }
    }
}

3 Answers 3

1

You need to create an array.

String arr[][] = new String[nRows][nCols];
Sign up to request clarification or add additional context in comments.

3 Comments

and then how can I get only 10 or 4 or / from that array ?
@lifemoveson - do you want to split an array? If yes then use String.split() method.
I am trying to read [0][0] and [0][1] separately and also each string from that list. I have edited my question. Hope it is clear.
0

I'm assuming you want to implement a method, because your implementation above looks more like a constructor. Here's my shot:

public String[][] matrix(int nRows, int nCols, String... exprArray) {
    String[][] m = new String[nRows][nCols];
    for (int i = 0; i < nRows; i++)
        for (int j = 0; j < nCols; j++)
            m[i][j] = exprArray[(i * nCols) + j];
    return m;
}

If you need this to be done in a constructor, simply call the above method inside your constructor (clearly, you'll have to declare an attribute of type String[][] to store the resulting matrix)

Comments

0

this may not answer your original quest, but i am trying to give another perspective

you may choose to impl the 2D array by 1D array like this and hide the impl details behind your getter

public class Matrix {

    private String[] data;
    private int colCount;

    public Matrix(int rowCount, int colCount, String... data) {
        this.data = new String[rowCount * colCount];
        System.arraycopy(data, 0, this.data, 0, data.length);

        this.colCount = colCount;
    }

    public String get(int row, int col) {
        return data[row * colCount + col];
    }
}

and you can simplify this further if your rowCount is the same as colCount

class SquareMatrix extends Matrix{

    public SquareMatrix(int size, String... data) {
        super(size, size, data);
    }
}

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.