所以我的代码正确地打印了一个具有相同尺寸(3x3、2x2)的矩阵,但不是像 3x2 这样的不相等的矩阵。循环有什么问题?
public Matrix(int d[][])
{
numRows = d.length; // d.length is the number of 1D arrays in the 2D array
if(numRows == 0)
numColumns = 0;
else
numColumns = d[0].length; // d[0] is the first 1D array
data = new int[numRows][numColumns]; // create a new matrix to hold the data
// copy the data over
for(int i=0; i < numRows; i++)
for(int j=0; j < numColumns; j++)
data[i][j] = d[i][j];
}
public String toString()
{
String doPrint="";
Matrix k = this;
Matrix l = new Matrix(new int[k.numRows][k.numColumns]);
for (int i = 0; i < l.numColumns; i++) {
for (int j = 0; j < l.numRows; j++)
doPrint = doPrint + k.data[i][j]+" ";
doPrint = doPrint + "\n";
}
return doPrint;
}
最佳答案
您正在混合方法 toString()
的嵌套 for
循环中使用的索引。
您在以下位置使用 i
表示行,使用 j
表示列:
doPrint = doPrint + k.data[i][j] + " ";
但是在循环中你交换了索引。您应该首先遍历行,然后遍历列:
for (int i = 0; i < l.numRows; i++)
for (int j = 0; j < l.numColumns; j++)
关于java - 以矩阵形式打印二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23798274/