Domanda

I'm not sure where I'm going wrong with my code and I'm still really new to learning sets so I apologize if my errors are easy fixes and should be noticeable. Nonetheless, I cannot figure this out.

I have to let the user enter a pair of sets A and B and then compute and print the intersection and union. (The universe is {1, 2, ... , 10} )

I will worry about robustness later, I just want to figure out how the user can manually enter the numbers for the sets.

Here is my code:

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);
  }
}

This is my output:

How many elements in Set A? 3 Enter a number 1-10: Enter a number 1-10: Enter a number 1-10: How many elements in Set B? 2 Enter a number 1-10: Enter a number 1-10: The union of A and B: [1, 2, 3] The intersection of A and B: [1, 2]

È stato utile?

Soluzione

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

There's nothing in this loop that inputs a number from the user. Instead, you're adding the loop index to the set, which means you're calling A.add(1), A.add(2), ...

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top