我正在开发一个关于eclipse的Matrix程序,目前我仍然坚持使用2种方法,其中我认为这是最简单的方法。我正在研究的第一种方法是从@Test案例中获取2个不同2D数组的总和,并在新的2D数组中返回总和。我已经有了一个2D数组实例变量。我被卡住的原因是因为方法中的参数。该参数不提供除类(Matrix)和变量(其他)之外的任何变量。所以我想知道如何开始这个方法,最重要的是返回sum数组。
我坚持的另一种方法是转置方法,你必须翻转给定2D数组的行和列。我知道我必须创建一个临时2D数组,以便将内容存储回原始的2D数组,但由于某种原因,它没有通过测试用例。如果有人可以帮我解决这两种方法,我们将不胜感激。
import java.util.Arrays;
public class Matrix {
private int[][] array;
private int[][] array2;
private int theRow;
private int theCol;
public Matrix(int[][] arrayOfArrays) {
// TODO Auto-generated constructor stub
array = new int[arrayOfArrays.length][arrayOfArrays[0].length];
for (int r = 0; r < arrayOfArrays.length; r++) {
for (int c = 0; c < arrayOfArrays[r].length; c++) {
array[r][c] = arrayOfArrays[r][c];
}
}
}
public int get(int row, int column) {
return array[row][column];
}
public int getNumberOfRows() {
int nRows = array.length;
return nRows;
}
public int getNumberOfColumns() {
int nCols = array[0].length;
return nCols;
}
public String toString() {
String res = "";
for (int r = 0; r < array.length; r++) {
for (int c = 0; c < array[r].length; c++)
res = res + array[r][c];
}
return res;
}
public Matrix sum(Matrix other) {
return sum;
}
public void scalarMultiply(int scalar) {
for (int r = 0; r < array.length; r++) {
for (int c = 0; c < array[0].length; c++) {
array[r][c] = array[r][c] * scalar;
}
}
}
public void transpose() {
int m = array.length;
int n = array[0].length;
int[][] transpose = new int [n][m];
int temp;
for (int r = 0; r < m; r++) {
for (int c = 0; c < n; c++) {
transpose[c][r] = array[r][c];
array[r][c] = array[c][r];
array[c][r] = transpose[c][r];
}
}
}
//The test cases for sum method and transpose method
@Test
public void testSum() {
int[][] a1 = { { 1, 2, 3 },
{ 5, 6, 7 } };
Matrix a = new Matrix(a1);
int[][] a2 = { { -2, -2, -2 },
{ 4, 4, 4 } };
Matrix b = new Matrix(a2);
Matrix c = a.sum(b);
assertEquals(-1, c.get(0, 0));
assertEquals(0, c.get(0, 1));
assertEquals(1, c.get(0, 2));
assertEquals(9, c.get(1, 0));
assertEquals(10, c.get(1, 1));
assertEquals(11, c.get(1, 2));
}
@Test
public void testTranspose() {
int[][] a1 = { { 1, 3, 5 },
{ 2, 4, 6 } };
Matrix a = new Matrix(a1);
a.transpose();
assertEquals(1, a.get(0, 0));
assertEquals(2, a.get(0, 1));
assertEquals(3, a.get(1, 0));
assertEquals(4, a.get(1, 1));
assertEquals(5, a.get(2, 0));
assertEquals(6, a.get(2, 1));
}
答案 0 :(得分:2)
您需要更改尺寸,例如,2x3 - &gt; 3×2。
import java.util.Arrays;
public class Matrix {
private int[][] array;
private int[][] array2;// remove this
private int theRow;// remove this
private int theCol;// remove this
public void transpose() {
int m = array.length;
int n = array[0].length;
int[][] transpose = new int [n][m];
for (int r = 0; r < m; r++) {
for (int c = 0; c < n; c++) {
transpose[c][r] = array[r][c];
}
}
array = transpose;
}
}