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