如何找到两组的交集和并集

时间:2014-02-11 00:57:27

标签: java set union intersection universe

我不确定我的代码在哪里出错,而且我仍然是学习集的新手,所以如果我的错误很容易修复并且应该引人注意,我会道歉。尽管如此,我无法弄清楚这一点。

我必须让用户输入一对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);
  }
}

这是我的输出:

集合A中有多少个元素? 3 输入数字1-10:输入数字1-10:输入数字1-10:设置B中有多少个元素? 2 输入数字1-10:输入数字1-10:A和B的并集:[1,2,3] A和B的交点:[1,2]

1 个答案:

答案 0 :(得分:1)

for (int j = 1; j <= elementsA; j++) {
    System.out.print("Enter a number 1-10: ");
    A.add(j);
}

此循环中没有任何内容可以从用户输入数字。相反,您将循环索引添加到集合中,这意味着您正在调用A.add(1)A.add(2),...