In: Computer Science
This question is about the class Set, as discussed in the lectures. It represents a finite set of int’s. Relevant parts of Set are shown below. The integer count holds the number of elements in the Set. The array elements holds the elements themselves. The class Set also has public methods addElement, equals, isIn, and toString. They are defined as in the lectures, and you can use them if you need to.
class Set
{
private int count;
private int [] elements;
}
Write a public method for Set called both that takes another Set as its only parameter. The method both must return the number of elements that are in both Set’s.
For example, suppose that s1 is an instance of Set with elements 0, 2, 3, and 5. Also suppose that s2 is an instance of Set with elements 0, 1, 3, 4, and 11. Then s1.both(s2) must return 2, because there are two elements 0 and 3 that are in both sets. This is only an example! For full credit, your method both must work for any Set’s, not just the ones mentioned here.
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package settest; import java.util.Scanner; /** * * @author pihu */ public class Set { private int count; private int[] elements; public Set(int count, int[] elements) { this.count = count; this.elements = elements; } public int[] getElements() { return elements; } public void setElements(int[] elements) { this.elements = elements; } public int both(Set s) { Set s1; int count=0; Set s2; if(this.elements.length>s.elements.length) { s1=this; s2=s; } else { s1=s; s2=this; } for(int i=0;i<s1.elements.length;i++) { int temp=s1.elements[i]; for(int j=0;j<s2.elements.length;j++) { if(temp==s2.elements[j]){ System.out.println(temp); count++; } } } return count; } public static void main(String args[]) { System.out.println("Enter size of one set"); Scanner input=new Scanner(System.in); try{ int count1=input.nextInt(); System.out.println("Enter set1 elements"); int set1_elem[]=new int[count1]; for(int i=0;i<count1;i++) { int set1=input.nextInt(); set1_elem[i]=set1; } Set set1=new Set(count1,set1_elem); System.out.println("Enter size of second set"); input=new Scanner(System.in); count1=input.nextInt(); System.out.println("Enter set2 elements"); int set2_elem[]=new int[count1]; for(int i=0;i<count1;i++) { int set2=input.nextInt(); set2_elem[i]=set2; } Set set2=new Set(count1,set2_elem); System.out.println(".............."); System.out.println("elements same in both set are"); int Count= set1.both(set2); System.out.println("Total "+Count+" No of Elements are same in both set"); }catch(Exception ne){System.out.println("Invalid inputs plz try again");} } }