为什么我的方法在更改数组元素时不返回 false?



我正在尝试检查我的 2D 数组是否对称。我写了一个方法来检查数组是否对称。它总是返回 true,即使我更改了输入数组中的元素也是如此。 我做错了什么?

这是我的代码:

public class learnigBoolean
{
    public static void main(String[] args)
    {
        int[][] array = {
            { 1,  1,  4, -1},
            { 1,  5,  0, -1},
            { 4,  0,  1, -4},
            {-1, -1,  4, 10}
        };
        System.out.println(symetrisk(array));
    }
    public static boolean symetrisk(int[][] f)
    {
        for (int out = 0; out < f.length; out++) {
            for (int in = 0; in < f[out].length; in++) {
                if (f.length == f[out].length && f[out][in] == f[out][in]) {
                    return true;
                }
            }
        }
        return false;
    }
}
if(f.length==f[out].length && f[out][in]==f[out][in])

第一个检查确保你的矩阵是平方的,第二个检查什么都不做!您正在将每个元素与自身进行比较。

你不是说:

if(f.length==f[out].length && f[out][in]==f[in][out])

但正如迈克尔·费斯特所说,你的回报声明是有问题的。

你需要这样的东西:

   for (int out = 0; out < f.length; out++) {
        for (int in = 0; in < f[out].length; in++) {
            if (f.length != f[out].length || f[out][in] != f[in][out])) {
                return false;
            }
        }
    }
    return true;

通过反转检查,可以确保在返回 true 之前检查每个元素。

可以这样想:你只需要找到一个不满足条件的元素,说你的数组不是对称的。但是,您需要先检查每个元素,然后才能说数组是对称的。

您正在做相反的事情,说数组仅在一次检查后是对称的。

f[out][in] == f[out][in] 

将始终返回 true。同样调用"return true"将在第一个正匹配后退出循环,即:

f[0][0] == f[0][0] 

也总是正确的。

如果你想提高效率,你可能想将第二个循环初始化为"out"以防止两次检查同一对,跳过检查数字本身,并在发现不匹配时立即退出循环,如下所示:

public static boolean symetrisk(int[][] f)
{
    for (int out = 0; out < f.length; out++) {
        if (f.length == f[out].length) //only need to check this once per row.
        {
            for (int in = out + 1; in < f[out].length; in++) 
            {
                if (f[out][in] != f[in][out]) 
                {
                        return false; //once we find a non-matching value we stop checking
                }
            }
        } 
        else 
        {
            return false; //non-square array.
        }           
    }
    return true;
}

最新更新