简体   繁体   中英

Store String… array in 2D array

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

        }
    }
}

您需要创建一个数组。

String arr[][] = new String[nRows][nCols];

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)

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);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM