繁体   English   中英

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

[英]Why does my method not return false when I change the array's element?

我试图检查我的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])

但正如Michael Faisst所说,你的退货声明是有问题的。

你需要这样的东西:

   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] 

永远都会回归真实。 同样调用“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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM