gpt4 book ai didi

Java 比较数组数据,无论大小或顺序如何

转载 作者:太空宇宙 更新时间:2023-11-04 15:01:45 24 4
gpt4 key购买 nike

我正在编写一个基本程序来比较两个数组中的数据。顺序并不重要,重复的数字也不重要。当前输出表明数组数据是相同的。这不是我想要发生的事情,因为数组数据不同。这是我现在的代码:

public class Algorithm1{
public static void main (String[] args){

int[] array1 = {1, 2, 3};
int[] array2 = {1, 2, 3, 4, 5, 6};
int matchCount = 0;
boolean match = false;

for(int j = 0; j < array1.length;j++) {
for(int i = 0; i < array2.length;i++){
if(array1[j] == array2[i])
matchCount++;


}
}
if(matchCount >= array1.length && matchCount >= array2.length)
match = true;

if(match = true){
System.out.println("The data in the arrays is the same.");
}
else if(match = false){
System.out.println("The data in the arrays is different.");
}
}
}

最佳答案

只需将 if(match = true) 替换为 if(match == true),或者更简单,if(match),你应该没问题;)

你写道:

if(match = true) {
System.out.println("The data in the arrays is the same.");
}

实际上,if(match = true):

  • match设置为true
  • 测试前一个表达式是否为true...并输入if:)
<小时/>

作为旁注,我想指出您不需要在 else 子句中指定 if(match==false)...因为如果我们输入该 else,它已经意味着match != true(即:match == false)。

干杯!

关于Java 比较数组数据,无论大小或顺序如何,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22494182/

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