存储字符串.二维数组中的数组



我有一个函数,它的值在矩阵形式与字符串…数组(在JDK 1.4中为var args)格式。我可以添加2D数组的值并添加数组中的值吗?

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

和函数调用:

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

我假设你想实现一个方法,因为你上面的实现看起来更像一个构造函数。这是我的镜头:

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

如果您需要在构造函数中完成此操作,只需在构造函数中调用上述方法(显然,您必须声明String[][]类型的属性来存储生成的矩阵)

这可能不能回答你最初的问题,但我试图给出另一个角度

你可以选择像这样将2D数组通过1D数组来实现并将impl细节隐藏在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];
    }
}

,如果rowCount与colCount相同,可以进一步简化这一点

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

最新更新