【发布时间】:2016-03-03 03:01:52
【问题描述】:
更新: 当我检查两个矩阵是否相等时,我的程序总是返回 false。初始化和复制工作正常,我可以通过控制台验证两个矩阵在打印后是否相同。不管我做什么,equals方法总是返回false!
// 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为零怎么办?另外,我认为您可能需要重新考虑循环中的逻辑(您的内部循环只会在返回之前运行一次)。 -
你的 for 可以运行 0 次,然后没有返回语句
-
用默认 false 初始化一个布尔值,必要时更改它并最终返回它。您在循环内返回一个值,但循环可能永远不会开始。
-
试试我的解决方案吧
-
尝试调试或打印子结果。在 Equals 方法中打印出 otherMatrix。如果这是正确的,那么在 for 循环中的值以及它们为什么不一样。
标签: java oop matrix methods equals