我不确定我的代码哪里出了问题,而且我对学习集还是很陌生,所以如果我的错误很容易修复并且应该很明显,我深表歉意。尽管如此,我无法弄清楚这一点。
我必须让用户输入一对集合 A 和 B,然后计算并打印交集和并集。(宇宙是 {1, 2, ... , 10} )
稍后我会担心健壮性,我只想弄清楚用户如何手动输入集合的数字。
这是我的代码:
import java.util.*;
public class sets {
public static void main (String[] args) {
Scanner in = new Scanner(System.in);
//declare the universe in a set
Set universe = new HashSet();
for (int i = 1; i <= 10; i++) {
universe.add(i);
}
//Ask the user how many elements and declare set A
System.out.print("How many elements in Set A? ");
int elementsA = in.nextInt();
Set A = new HashSet();
for (int j = 1; j <= elementsA; j++) {
System.out.print("Enter a number 1-10: ");
A.add(j);
}
//Ask the user how many elements and declare set B
System.out.print("How many elements in Set B? ");
int elementsB = in.nextInt();
Set B = new HashSet();
for (int k = 1; k <= elementsB; k++) {
System.out.print("Enter a number 1-10: ");
B.add(k);
}
//get the union of the sets
Set union = new HashSet(A);
union.addAll(B);
System.out.println("The union of A and B: "+union);
//get the intersection of the sets
Set intersect = new HashSet(A);
intersect.retainAll(B);
System.out.println("The intersection of A and B: "+intersect);
}
}
这是我的输出:
Set A 中有多少个元素?3 输入数字 1-10:输入数字 1-10:输入数字 1-10:Set B 中有多少个元素?2 输入数字 1-10:输入数字 1-10:A 和 B 的并集:[1, 2, 3] A 和 B 的交集:[1, 2]