Reputation: 1691
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]);
}
}
}
Upvotes: 1
Views: 4228
Reputation: 1726
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);
}
}
Upvotes: 0
Reputation: 236170
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)
Upvotes: 0
Reputation: 94653
You need to create an array.
String arr[][] = new String[nRows][nCols];
Upvotes: 1