java - 我编写的代码有问题吗?

标签 java set-intersection set-difference

所以我们的项目都是关于集合的,它应该显示并集、交集、差集,我对我的代码有疑问,因为在我们老师给我们的示例中,集合的元素已经给出,并且在输出中并集和交集中没有“空”结果,但我们的挑战是让元素成为用户输入,并且在我的代码中我的并集和交集中有一个“空”结果。这样可以吗?

  public static void main(String[] args) {


    Scanner scan = new Scanner(System.in);
    Set<Integer> a = new HashSet<Integer>();
    a.addAll(Arrays.asList(new Integer[5]));
    for () {
       //scan code...
    }





    Set<Integer> b = new HashSet<Integer>();
    b.addAll(Arrays.asList(new Integer[5]));
    for () {
       //scan code...
    }

    // UNION

    Set<Integer> union = new HashSet<Integer>(a);
    union.addAll(b);
    System.out.print("\nUnion of the two Set: ");
    System.out.println(union);


    // INTERSECTION

    Set<Integer> intersection = new HashSet<Integer>(a);
    intersection.retainAll(b);
    System.out.print("Intersection of the two Set: ");
    System.out.println(intersection);


    // DIFFERENCE

    Set<Integer> difference = new HashSet<Integer>(a);
    difference.removeAll(b);
    System.out.print("Difference of the two Set: ");
    System.out.println(difference);

}

输出:(老师给出的代码!)

两个集合的并集[0, 1, 2, 3, 4, 5, 7, 8, 9]

两个 Set[0, 1, 3, 4] 的交集

两个Set的区别[2,8,9]

我的输出:

A组:

3 4 2 1 0

B组:

7 4 1 9 8

两个集合的并集:[null, 0, 1, 2, 3, 4, 7, 8, 9]

两个集合的交集:[null, 1, 4]

两个集合的差异:[0, 2, 3]

最佳答案

由于代码中的这两行,您有 null :

        a.addAll(Arrays.asList(new Integer[5]));
        b.addAll(Arrays.asList(new Integer[5]));

只需删除这两行,您的代码就应该可以工作。

关于java - 我编写的代码有问题吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58253726/

相关文章:

r - 将两列列表类型行与 dplyr 进行比较

python - 如果元素等于某个容差,我可以使用 numpy 快速设置 float 差异吗

java - 多对多 JPA Hibernate 通过连接表映射复合键错误

c++ - C++ 中一组集合的高效集合交集

java - 优先级队列并集、交集、差异编译但不返回输出

java - 当字符串中有逗号时,无法找到两个字符串数组的正确交集

JQ:两个数组的setdiff

java - Maven 代码覆盖率

java - 您可以在 Eclipse 和 IntelliJ 上标准化警告吗?

java - 无法使用构造函数?