I need help creating a Java program. I need this program to be as basic and simp
ID: 3820570 • Letter: I
Question
I need help creating a Java program. I need this program to be as basic and simple as possible please. Please see instructions and check the input/output example to make sure you see what exactly I need. Thank you.
Write a Java program that uses one-dimensional arrays to implement finite sets and set operations union, difference, and intersection.
Specific requirements:
1. Elements of a set are integers from 1 to 20.
2. Use 0 as the end of a set. See examples below.
3. Prompt user to enter two sets A and B and calculate B union A, B A, and A intersection B
Here is a sample:
Input (user input example)
Enter elements of set A: 2 4 6 7 9 0
Enter elements of set B: 1 3 5 7 9 10 18 0
Output
Union of A and B is: 1, 2, 3, 4, 5, 6, 7, 9, 10, 18
Intersection of A and B is: 7, 9
Difference of A and B is: 2, 4, 6
Explanation / Answer
package org.students;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class SetOperations1 {
public static void main(String[] args) {
//Declaring a variable
int num=0;
//Creating ArrayList which holds Integers
ArrayList<Integer> arl1=new ArrayList<Integer>();
ArrayList<Integer> arl2=new ArrayList<Integer>();
//Scanner object is used to get the inputs entered by the user
Scanner sc=new Scanner(System.in);
//Getting the set#A elements entered by the user and populate them into ArrayList
System.out.print("Enter elements of SetA :");
while(true)
{
num=sc.nextInt();
if(num!=0)
arl1.add(num);
else
break;
}
//Getting the set#B elements entered by the user and populate them into ArrayList
System.out.print(" Enter elements of SetB :");
while(true)
{
num=sc.nextInt();
if(num!=0)
arl2.add(num);
else
break;
}
Set set1=new HashSet<Integer>(arl1);
Set set2=new HashSet<Integer>(arl2);
Set set3=new HashSet<Integer>(arl1);
Set set4=new HashSet<Integer>(arl2);
Set set5=new HashSet<Integer>(arl1);
Set set6=new HashSet<Integer>(arl2);
//Finding B union A
set2.addAll(set1);
System.out.print("Union of B and A is:");
System.out.print(set2);
//Finding intersection of A and B
set3.retainAll(set4);
System.out.print(" Intersection of A and B is:");
System.out.print(set3);
set3.retainAll(set4);
//Finding difference between A and B
System.out.print("Difference of A and B is:");
set5.removeAll(set6);
System.out.print(set5);
}
}
___________________
Output:
Enter elements of SetA :2 4 6 7 9 0
Enter elements of SetB :1 3 5 7 9 10 18 0
Union of B and A is:[1, 2, 18, 3, 4, 5, 6, 7, 9, 10]
Intersection of A and B is:[7, 9]
Difference of A and B is:[2, 4, 6]
__________Thank You
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.