比较两个数组的元素

时间:2016-03-05 18:13:17

标签: java arrays static-methods boolean-expression

我的方法接受两个整数数组,如果

则返回true
  1. 数组长度相同
  2. 每个a.element都小于同一索引的b.element。
  3. 除了int[] a = {1, 2, 3}int[] b = {4, 5, 1}之外,它适用于我的所有测试用例。即使a[2] > b[2],它也会返回true。 digitDifference支票无法正常运行,但我无法看到错误。

    public static boolean allLess(int[] a, int[] b) {
        int i = 0;
        boolean sameLength = (a.length == b.length);
        boolean digitDifference = (a[i] < b[i]);
        for (i = 0; i <= a.length - 1; i++) {}
        return (sameLength && digitDifference);
    }
    

4 个答案:

答案 0 :(得分:3)

您的方法只比较每个数组中的第一个元素 - 比较是在for循环之外(它是空的!)而不是在它内部完成的。把它移到那里,你应该没事。

值得注意的是,在这种情况下使用早期返回惯用法会有助于生成更容易阅读的代码,因为您不需要继续“拖动”当前状态,只需在其中一个条件下快速失败坏了:

public static boolean allLess(int[] a, int[] b) {
    if (a.length != b.length) {
        return false;
    }
    for (i = 0; i <= a.length - 1; i++) {
        if (a[i] >= b[i]) {
            return false;
        }
    }
    return true;
}

答案 1 :(得分:2)

您的for循环不执行任何操作,因此您只是比较数组的第一个索引中的元素。

您的代码应如下所示:

public static boolean allLess(int[] a, int[] b) {
    boolean sameLength = (a.length == b.length);
    if (!sameLength)
        return false;
    boolean digitDifference = true;
    for (int i = 0; i <= a.length - 1 && digitDifference; i++) {
        digitDifference = (a[i] < b[i]);
    }
    return digitDifference;
}

现在,for循环会比较具有相同索引的每对元素,并在找到违反(a[i] < b[i])要求的对后终止。

没有标志的另一个等效实现:

public static boolean allLess(int[] a, int[] b) {
    if (a.length != b.length)
        return false;
    for (int i = 0; i <= a.length - 1; i++) {
        if (a[i] >= b[i])
            return false;
    }
    return true;
}

答案 2 :(得分:2)

digitDifference在循环之前初始化,并比较两个数组的第一个元素,因为此时i的值为0。你永远不会比较数组的其他元素。必须在内部循环中进行比较。

顺便说一下,你的循环体甚至没有一条指令。

答案 3 :(得分:2)

您需要检查以比较两个数组的长度,但您只能在方法结束时对其进行操作。与任何其他语言一样,Java允许您在方法中使用多个return语句,因此我的建议是在您执行检查后立即从该方法返回:

if (a.length != b.length)
   return false;

其次,代码中的digitDifference语句仅评估一次,数组中的第一个元素。我相信,你希望for循环在数组中的每个元素上多次执行比较,但是,你将循环的主体留空了。

for (i = 0; i <= a.length - 1; i++) {
    if(a[i] >= b[i])
       return false;
}

同样,我的建议是,一旦你发现其中一个元素违反你的约束,就会立即返回。并且在for循环之后只有一个return true;,这将表明所有元素都满足约束a[i] >= b[i]

相关问题