Java集合计算器:寻找集合的补充

时间:2018-12-09 21:03:55

标签: java arrays set calculator complement

编码一组补码时遇到麻烦。例如,如果集合A(x)= {1,2,3,4}且集合B(y)= {5,2,3,8}补数应为xy = {1,4}或yx = {5 ,8}。为了实现此目的,我应该在代码中进行哪些更改?

for (i = 0; i < x; i++) {
    for (int k = 0; k < y; k++) {
        if (a[i] == b[k]) {
            flag = 1;
            break;
        } else {
            flag = 0;
        }
    }

    if (flag == 0) {
        c[z++] = a[i];
    }
}

System.out.print("Complement:");
System.out.print("[ ");
for (i = 0; i < x; i++) {

    System.out.print(a[i] + ",");
}
System.out.print(" ]");

1 个答案:

答案 0 :(得分:0)

您应该打印结果c [i]而不是a [i]。

for (int i = 0; i < z; i++) {
  System.out.print(a[i] + ",");
}