我在创建此设置计算器时遇到麻烦,它在某一点上还可以正常工作,但我不知何故把它弄乱了,现在它实际上再也找不到联合,交集,差值和补码了。而且我的+ n只会打印1而不是他们输入的设置。
有人可以帮我吗?我可能做了一些极端的事情:(谢谢。
AdvancedTagUIImageView
答案 0 :(得分:0)
缺少的部分是将值添加到初始集合A
和B
的方法,您可以要求多个值,然后要求值。也不要使用2个不同的Scanners
仅使用一个
Set<Integer> A = new HashSet<>();
System.out.print("Enter set A, How many values do you want in it ? ");
int n = sc.nextInt();
for (int i = 0; i < n; i++) {
System.out.print("Write a value to add : ");
A.add(sc.nextInt());
}
Set<Integer> B = new HashSet<>();
System.out.print("Enter set B, How many values do you want in it ? ");
int v = sc.nextInt();
for (int i = 0; i < v; i++) {
System.out.print("Write a value to add : ");
B.add(sc.nextInt());
}
在difference
部分出现一个拼写错误:
difference.addAll(A);
而不是intersection.addAll(A);
您将拥有:
Enter set A, How many values do you want in it ? 5
Write a value to add : 1
Write a value to add : 2
Write a value to add : 3
Write a value to add : 4
Write a value to add : 5
Enter set B, How many values do you want in it ? 5
Write a value to add : 4
Write a value to add : 5
Write a value to add : 6
Write a value to add : 7
Write a value to add : 8
Union of the two Sets is: [1, 2, 3, 4, 5, 6, 7, 8]
Intersection of the two Sets is: [4, 5]
Difference of the two Sets is: [1, 2, 3]
Complement of the two Sets is:[6, 7, 8]
提示 对于您所有的4个操作,您都可以简化
Set<Integer> union = new HashSet<Integer>();
union.addAll(A);
// into
Set<Integer> union = new HashSet<Integer>(A);