gpt4 book ai didi

java - 我正在编写一个程序来比较两个数组,但我无法让它将数组与空元素进行比较

转载 作者:行者123 更新时间:2023-12-02 01:45:46 26 4
gpt4 key购买 nike

我的代码粘贴在下面。该程序在不同类型的二维数组上运行良好,如果它们相同,则返回“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;
}
}

最佳答案

将此检查添加到 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++) {
//...
}
}
}
}

附注

您的代码经过一些修正后可以正常工作。也许我给你一个想法,如何改进它。这个怎么样:

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;
}

关于java - 我正在编写一个程序来比较两个数组,但我无法让它将数组与空元素进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53687847/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com