Suppose that you and your mom are friends on Facebook, and you want to figure ou
ID: 3546311 • Letter: S
Question
Suppose that you and your mom are friends on Facebook, and you want to figure out the friends you both have in common.
One way of doing this woule be to treat your friends list as an array and Mom's friends list as another array. Then, the problem of finding the common friends would be solvable by finding the intersection ( set of common elements ) between those two arrays. Assume that each friend is represented by a unique numerical ID number.
Write a program that accomplishes this task. Your program should include these three methods:
public static int[] readFriendIDs()
This method should allow the user to enter in a list of ID numbers, store those numbers into an array, and return the array that was created. Before allowing the user to enter the list, the method should ask the user to enter how large the array should be.
public static void displayCommonFriendIDs (int[] a, int[] b)
This method should take two arrays of friend IDs as parameters and display a list of all the IDs that appear in both a and b (regardless of order). The method should also display the count of common friends. Assume that both a and b contain distinct elements - that is, within each array there are no numbers repeated.
public static void main (String [] args)
The main method should call readFriendIDs twice to allow the user to enter in two lists of friend IDs. Then it should call displayCommonFriendIDs on those two lists to show the intersection.
Explanation / Answer
import java.util.Scanner;
public class FindFriends {
static int[] a,b;
private static Scanner input;
public static int[] readFriendIDs(){
input = new Scanner(System.in);
int[] a= new int[input.nextInt()];
for(int i=0;i<a.length;i++){
System.out.print("Enter "+(i+1)+" ID : ");
a[i]=input.nextInt();
}
return a;
}
public static void displayCommonFriendIDs (int[] a, int[] b){
System.out.println("Common Friend ID's are :");
for(int i=0;i<a.length;i++){
for(int j=0;j<b.length;j++){
if(a[i]==b[j]){
System.out.println(a[i]);
}
}
}
}
public static void main (String [] args){
System.out.print("Enter Number of Friend's in Mom's account : ");
a=readFriendIDs();
System.out.print("Enter Number of Friend's in Child's account : ");
b=readFriendIDs();
displayCommonFriendIDs(a, b);
}
}
#########################SAMPLE OUTPUT##########################
Enter Number of Friend's in Mom's account : 5
Enter 1 ID : 12
Enter 2 ID : 3
Enter 3 ID : 4
Enter 4 ID : 5
Enter 5 ID : 6
Enter Number of Friend's in Child's account : 2
Enter 1 ID : 5
Enter 2 ID : 6
Common Friend ID's are :
5
6
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.