美好的一天。我对 boolean 方法中的 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 语句中的值正确并在最后返回 false 时,我没有得到所需的输出。(对于任何输入的数字来说,它实际上都是 true)
考虑一下:
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 显然不同。 但我认为逻辑并没有改变...... 是否有一定的规则规定 return 语句的顺序? 或者我的代码中存在逻辑问题?
最佳答案
所以我不确定你是否只是看代码太久而没有看到这一小行代码,但由于第一个 if 语句,它总是返回 true。
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;
}
如果长度相等,第一个 if 语句将始终返回 true。您给出的示例具有相同长度的矩阵,因此返回 true。 编辑***** 您的 for 语句也将在矩阵之间的第一次匹配时返回 true。查看 if 语句,两个矩阵相等的第一个索引,返回导致代码跳出函数并返回 true,而不考虑第一个相似性之后的其他情况。调用任何return语句后,该函数就会被放弃,不再执行任何return语句调用后的代码。
关于java - Java boolean 方法最后返回 true 和 false 语句的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61414057/