有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何求两个集合的交和并

我不确定我的代码哪里出了问题,而且我对学习集还是一个新手,所以如果我的错误很容易修复,应该引起注意,我向您道歉。尽管如此,我无法理解这一点。

我必须让用户输入一对集合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) 个答案

  1. # 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)