【发布时间】:2020-08-08 08:41:39
【问题描述】:
美好的一天。我对布尔方法中的 true\false 返回调用有点困惑。 所以代码是:
public class CheckOut {
public static void main(String[] args) {
int[][] m = new int[3][3];
int[][] m1 = new int[m.length][m[0].length];
System.out.println("Enter the nums for the first matrix : ");
getM(m);
System.out.println("Enter the nums for the second matrix : ");
getM(m1);
System.out.println(strictlyIdentical(m, m1));
}
static int[][] getM(int[][] m) {
Scanner sc = new Scanner(System.in);
for (int i = 0; i < m.length; i++) {
for (int j = 0; j < m[i].length; j++) {
m[i][j] = sc.nextInt();
}
}
return m;
}
static boolean strictlyIdentical(int[][] m, int[][] b) {
if (m.length != b.length && m[0].length != b[0].length) {
return false;
}
for (int i = 0; i < m.length; i++) {
for (int j = 0; j < m[i].length; j++) {
if (m[i][j] != b[i][j]) {
return false;
}
}
}
return true;
}
}
上述方法工作得很好,如果两个矩阵相同,则返回 true,但是
为什么当我比较它们的正确性并返回 true 如果 if 语句中的 val 正确并在最后返回 false 时,我没有得到所需的输出。(对于任何输入的数字,它实际上都是真的)
考虑一下:
static boolean strictlyIdentical(int[][] m, int[][] b) {
if (m.length == b.length && m[0].length == b[0].length) {
return true;
}
for (int i = 0; i < m.length; i++) {
for (int j = 0; j < m[i].length; j++) {
if (m[i][j] == b[i][j]) {
return true;
}
}
}
return false;
}
}
现在我正在比较它们的相似性而不是差异的值,如果我可以这么说的话...... 如果给定以下输入,则此代码的输出如下:
Enter the nums for the first matrix :
12 3 4 3 2 1 2 3 3
Enter the nums for the second matrix :
1 2 3 2 3 2 1 2 3
true
所以前面的方法返回 true 而 nums 显然不同。 但在我看来,逻辑并没有改变...... 是否有特定规则规定返回语句的顺序? 还是我的代码中存在逻辑问题?
【问题讨论】:
-
您根本无法交换真假并期望得到相同的结果。第一个实现是正确的,因为它说:
if there is at least one index containing different elements, then the arrays are not equal.第二个实现不正确,因为它说if there is at least one index containing the same elements, then the arrays are equal这显然不是你想要的
标签: java methods return boolean comparison