更新: 当我检查两个矩阵是否相等时,我的程序总是返回false。初始化和复制工作正常,我可以通过控制台验证两个矩阵在打印后是否相同。不管我做什么,equals方法总是返回false!Java OOP类矩阵方法等于
// Class Matrix (Matrix.java)
import java.util.Scanner;
import java.util.Random;
public class Matrix {
private int size;
private int[][] table = new int[MAX][MAX];
//Default constructor
public Matrix() {
size = 0;
}
//Alternate constructor
public Matrix(int s) {
size = s;
}
//Method to initiate a matrix with random values
public void init(int low, int up) {
Random rand = new Random();
for (int r = 0; r < size; r++) {
for (int c = 0; c < size; c++)
table[r][c] = rand.nextInt(up - low + 1) + low;
}
}
//Method to copy the matrix
public void copy(Matrix a) {
for (int r = 0; r < size; r++) {
for (int c = 0; c < size; c++)
table[r][c] = a.table[r][c];
}
}
//Method to compare two matrices for equality
public boolean equals(Object obj) {
boolean result = false;
if (obj instanceof Matrix) {
Matrix otherMatrix = (Matrix) obj;
for (int r = 0; r < size; r++) {
for (int c = 0; c < size; c++)
//problem solved!
//previous:
//result = (table[r] == otherMatrix.table[r] && table[c] == otherMatrix.table[c]);
//fixed
result = (table[r][c] == otherMatrix.table[r][c]);
}
}
return result;
}
客户端来进行测试:
first.init(LOW, UP);
System.out.println("The original matrix is:");
first.print();
System.out.println("The copy of this matrix is: ");
result.copy(first);
result.print();
System.out.println("Testing for equality. Should be equal!!");
if (result.equals(first))
System.out.println("The matrices are equal!!");
else
System.out.println("The matrices are NOT equal!!");
如果'size'是零?另外,我认为你可能想重新考虑你的循环中的逻辑(你的内循环只会在返回之前运行一次)。 – ajshort
您的for可以运行0次,然后不返回语句 – DDan
用默认false初始化一个布尔值,如有必要,更改它并最终返回它。你在循环中返回一个值,但循环可能永远不会开始。 –