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

B: Programming (FindFriends) Create a Java program FindFriends. Your program wil

ID: 3591477 • Letter: B

Question

B: Programming (FindFriends) Create a Java program FindFriends. Your program will have a method that takes a Person object and a String as input. The method returns an integer (int) which is the number of friends the person has with the given input name (input string). The method will be called numberOfFriends Your program must first create the following Person object: "Cat" who was born in 2012. Cat has two friends: "Dog", who was born in 2011 and "Eel", who was born in 1997. Both Dog and Eel each have a single friend (who is Cat). Your program should then ask for user input (using a Scanner object) for a name. Using your numberOfFriends method, many friends Cat has with the input name. Finally, your program will output a message like the following: if the input name was "Owl", then the output would be Cat has 0 friends named Owl; if the input name "Eel", then the output would be Cat has 1 friends name Eel. Do not hard-code "Cat" (or "Owl or "Eel", etc) in the output message. It should print whatever name the Person object in your program has and the user input name. Your program should work correctly no matter what Person object we initially create. Your program must not create any indFrienda objects.

Explanation / Answer

import java.io.*;
import java.util.*;

class Person{

private String name;
private int year;
private ArrayList<Person> list;
public Person(String nm, int yr){
    name = nm;
    year = yr;
    list = new ArrayList<Person>();
}
public String getName(){
     return name;
}
public ArrayList<Person> getList(){
     return list;
}
public void addFriend(Person p){
     list.add(p);
}
public int numberOfFriends(String nm){
      int count = 0;
    
      for (int i = 0; i<list.size(); i++){
         
          if (list.get(i).getName().equals(nm))
             count++;
      }
      return count;
}
}

public class FindFriends{

  
   public static void main(String args[]){
      Person p = new Person("John",1980);
      Person p1 = new Person("Marry",1981);
      Person p2 = new Person("Nick",1982);
      p.getList().add(p1);
      p.getList().add(p2);
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter the name : ");
      String name = sc.nextLine();
      int count = p.numberOfFriends(name);
      System.out.println(p.getName() + " has " + count + " friends name " + name);
     

   }
}