Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a program called Sets.java that reads two sets of numbers from the keyboar

ID: 3624736 • Letter: W

Question

Write a program called Sets.java that reads two sets of numbers from the keyboard and prints the intersection of the two sets in any order (without duplicates), and prints the union of the two sets in any order (without duplicates).

Sample Run #1

Just for illustration, what you type looks like this:
Enter values for first set, ending with -1
1 3 9 7 5 -1
Enter values for second set, ending with -1
2 3 5 7 -1
Intersection: 3 7 5
Union: 1 3 9 7 5 2

Sample Run #2

Enter values for first set, ending with -1
0 3 -30 -1
Enter values for second set, ending with -1
123456789 3 4 -1
Intersection: 3
Union: 0 3 -30 123456789 4

Sample Run #3

Enter values for first set, ending with -1
9
6
-1
Enter values for second set, ending with -1
3
2 -1
Intersection:
Union: 9 6 3 2

Explanation / Answer

import java.util.*;

public class Sets
{
public static void main(String[] args)
{
// sets
Set<Integer> set1 = new TreeSet<Integer>();
Set<Integer> set2 = new TreeSet<Integer>();

// keyboard input
Scanner kb = new Scanner(System.in);

System.out.print("Enter values for first set, ending with -1");

int temp;

while((temp = kb.nextInt()) != -1)
set1.add(temp);

System.out.print("Enter values for first set, ending with -1");

while((temp = kb.nextInt()) != -1)
set2.add(temp);

// compute intersection
Set intersection = new TreeSet<Integer>();

for(int i : set1)
if(set2.contains(i))
intersection.add(i);

// compute union
Set union = new TreeSet<Integer>();

for(int i : set1)
union.add(i);

for(int i : set2)
union.add(i);

// print intersection
System.out.print("Intersection: ");

for(int i : intersection)
System.out.print(i+" ");
System.out.println();

// print union
System.out.print("Union: ");

for(int i : union)
System.out.print(i+" ");
System.out.println();
}
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote