简体   繁体   English

将String…数组存储在2D数组中

[英]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. 我有一个函数,该函数具有String ... array(jdk 1.4中的var args)格式的矩阵形式的值。 Can I add the values having 2D array and adding the values from the array in it. 我可以添加具有2D数组的值并在其中添加数组中的值。

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) 如果您需要在构造函数中完成此操作,只需在构造函数内部调用上述方法(显然,您必须声明String [] []类型的属性以存储生成的矩阵)

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 您可以选择像这样用1D数组隐含2D数组,并将隐含细节隐藏在您的吸气剂后面

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 如果您的rowCount与colCount相同,则可以进一步简化

class SquareMatrix extends Matrix{

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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