[英]Store String… array in 2D array
我有一個函數,該函數具有String ... array(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 [] []類型的屬性以存儲生成的矩陣)
這可能無法回答您最初的要求,但是我正在嘗試提供另一種觀點
您可以選擇像這樣用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];
}
}
如果您的rowCount與colCount相同,則可以進一步簡化
class SquareMatrix extends Matrix{
public SquareMatrix(int size, String... data) {
super(size, size, data);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.