首页 文章

我'm writing a program that compares two arrays together, but I can' t得到它来比较具有空元素的数组

提问于
浏览
0

我的代码粘贴在下面 . 该程序在不同类型的二维数组上工作正常,如果它们相同则返回“true”,如果它们不是,则返回false . 但是,当两个数组的维度都包含空元素时,会出现一个小错误:

int a[][] = {{},{}};
    int b[][] = {{},{}};

这个输入需要返回“true”,因为数组仍然是相同的,但是我得到的数组索引超出了边界错误 . 有什么方法可以让我的程序认识到这两个数组仍然相同吗?

public class ArrayCompare {
    public static void main(String[] args){
        int a[][] = {{},{}};
        int b[][] = {{},{}};
        boolean result = equals(a,b);
        System.out.println(result);
    }

    public static boolean equals(int[][] a, int[][] b) {
        boolean boo = true;
        if (a != null && b != null) {
          if (a.length != b.length || a[0].length != b[0].length || a[1].length != b[1].length)
              boo = false;
          else
              for (int i = 0; i < b.length; i++) {
                  for(int j =0; j <b.length; j++) {
                      if (b[i][j] != a[i][j]) {
                          boo = false;    
                      }   
                  }

            }
        }else {
          boo = false;
        }
        return boo;
    }
}

2 回答

  • 0

    将此检查添加到 else 语句 a[i].length > 0

    else {
        for (int i = 0; i < b.length; i++) {
            if (a[i].length > 0) {  // add check for empty array
                for (int j = 0; j < b.length; j++) {
                    //...
                }
            }
        }
    }
    

    P.S.

    您的代码可以正常进行一些修正 . 可能我会给你一个想法,如何改进它 . 这个如何:

    public static boolean equals(int[][] one, int[][] two) {
        if (one == null || two == null || one.length != two.length)
            return false;
    
        for (int row = 0; row < one.length; row++) {
            if (one[row].length != two[row].length)
                return false;
    
            for (int col = 0; col < one[row].length; col++)
                if (one[row][col] != two[row][col])
                    return false;
        }
    
        return true;
    }
    
  • 2

    您的代码中存在一个小的逻辑缺陷 . 在嵌套循环中,您应该遍历每个数组中的元素 .

    for (int i = 0; i < b.length; i++) {
        for(int j =0; j <b[i].length; j++) {// iterate over the number of elements of the current array
            if (b[i][j] != a[i][j]) {
                boo = false;
            }
        }
    }
    

相关问题