猿问

如何比较 Java 中的两个二维数组?

我是一个初学者,试图用 Java 编写一个函数,true如果两个传递的 2Dint类型数组在每个维度上的大小都相同,则返回该函数,false否则返回。要求是如果两个数组都是null你应该返回true. 如果一个是null,另一个不是,你应该返回false。


不知何故,我的代码出现错误:


public static boolean arraySameSize(int[][] a, int[][] b) {

    if (a == null && b == null) {

        return true;

    }

    if (a == null || b == null) {

        return false;

    }

    if (a.length == b.length) {

        for (int i = 0; i < a.length; i++) {

            if (a[i].length == b[i].length) {

                return true;

            }

        }   

    }

    return false;

}

任何帮助,将不胜感激!


编辑:问题是“运行时错误:空”


德玛西亚99
浏览 390回答 1
1回答

一只萌萌小番薯

你的逻辑看起来几乎是正确的。我看到的唯一问题是处理两个数组都不为空且具有相同第一维的情况的逻辑。如果任何索引没有匹配的长度,您应该返回 false:public static boolean arraySameSize(int[][] a, int[][] b) {&nbsp; &nbsp; if (a == null && b == null) {&nbsp; &nbsp; &nbsp; &nbsp; return true;&nbsp; &nbsp; }&nbsp; &nbsp; if (a == null || b == null) {&nbsp; &nbsp; &nbsp; &nbsp; return false;&nbsp; &nbsp; }&nbsp; &nbsp; if (a.length != b.length) {&nbsp; &nbsp; &nbsp; &nbsp; return false;&nbsp; &nbsp; }&nbsp; &nbsp; // if the code reaches this point, it means that both arrays are not&nbsp; &nbsp; // null AND both have the same length in the first dimension&nbsp; &nbsp; for (int i=0; i < a.length; i++) {&nbsp; &nbsp; &nbsp; &nbsp; if (a[i] == null && b[i] == null) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; continue;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; if (a[i] == null || b[i] == null) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return false;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; if (a[i].length != b[i].length) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return false;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return true;}按照下面的演示链接查看此方法正常工作的一些示例。
随时随地看视频慕课网APP

相关分类

Java
我要回答