Question

IN JAVA 04. Fourth Assignment – Facebook Friends We’ll continue with the Facebook application by enabling...

IN JAVA

04. Fourth Assignment – Facebook Friends We’ll continue with the Facebook application by enabling the ability to friend and defriend people through our driver program. In particular, you will need to add four new menu options: friend someone, de-friend someone, list friends, and recommend new friends. Of course, you’ll need to add new methods to the Facebook class to perform these actions. The first three of these new functions (friending, de-friending, and listing friends) are similar to the methods we wrote in 03. Third Assignment Binary File I/O – you should first prompt for the username of the FacebookUser doing the action. If there is no user with that username, display an error message. If the user exists, prompt for a password and make sure that what is entered matches the user’s password. For friending and defriending, you’ll also need to prompt for the username of the new or former friend. Again, if there is no user with that username, display an error message, otherwise, call the appropriate method for the FacebookUser object, passing it the object that represents the new/former friend. How should we go about recommending new friends? We’ll take the approach of recommending all of our friends’ friends and our friends’ friends’ friends, and so on. This is a perfect opportunity to use recursion – we can create a getRecommendations method that takes a FacebookUser as an argument. The method should return an ArrayList that contains all of the friends of the FacebookUser that is passed into it plus the result of calling the same getRecommendations method on all of that FacebookUser’s friends. Be careful not to add anyone to the list of recommendations if they are already on it – that could lead to an infinite loop. You will be graded according to the following rubric (each item is worth one point):  The driver menu contains the four new options  It is possible to add a friend at runtime  It is possible to remove a friend at runtime  It is possible to list a user’s friends  It is possible to get friend recommendations, and those recommendations are correct according to the requirements given above (i.e. they are all the friends of existing friends, and so on, without duplicates)  The getRecommendations method is recursive (usually assignments will not specify the approach you should take, but this is a special case since this topic is all about recursion)  Error messages are displayed for invalid usernames or passwords  The program compiles  The program runs  The program is clearly written and follows standard coding conventions Copyright © 2017, 2018 Sinclair Community College. All Rights Reserved.  Note: If your program does not compile, you will receive a score of 0 on the entire assignment  Note: If you program compiles but does not run, you will receive a score of 0 on the entire assignment  Note: If your Eclipse project is not exported and uploaded to the eLearn drop box correctly, you will receive a score of 0 on the entire assignment  Note: If you do not submit code that solves the problem for this particular assignment, you will not receive any points for the program’s compiling, the program’s running, or following standard coding conventions.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Driver.java


import java.io.IOException;
import java.util.Scanner;

public class Driver {

   public static void main(String[] args) throws IOException {

       Scanner keyboard = new Scanner(System.in);
       Facebook faceBook = new Facebook();

//       ObjectSerializing serialize = new ObjectSerializing();
//       ObjectDeserializing deserialize = new ObjectDeserializing();
//       System.out.println("***Test ObjectDeserialization***");
//       deserialize.deserialize();

       while (true) {
           System.out.println("Choose an option: 1. List users , 2. Add users, "
                           + "3. Delete users, 4. Get password hint, "
                           + "5. friend someone, 6. de-friend someone, 7. list friends, "
                           + "8. recommend new friends, 9. quit ");
           String op = keyboard.next();

           if (op.equalsIgnoreCase("1")) { // list
               faceBook.printUsers();

           } else if (op.equalsIgnoreCase("2")) { // add
               faceBook.addUser();

           } else if (op.equalsIgnoreCase("3")) { // delete
               faceBook.deleteUser();

           } else if (op.equalsIgnoreCase("4")) { // password hint
               faceBook.getPasswordHelp();

           } else if (op.equalsIgnoreCase("5")) { // friend
               faceBook.friend();

           } else if (op.equalsIgnoreCase("6")) { // de-friend
               faceBook.deleteUser();

           } else if (op.equalsIgnoreCase("7")) { // list
               faceBook.listFriends();

           } else if (op.equalsIgnoreCase("8")) { // recommend
               faceBook.getRecommendations();

           } else if (op.equalsIgnoreCase("9")) { // quit

               // create serialized object before program ends
//               System.out.println("***Test ObjectSerialization***");
//               System.out.println("***Creating serialized Facebook object***");
//               Facebook facebook = new Facebook("Homer Simpson", "Doughnuts");
//               serialize.serialize(facebook);
               System.out.println("");
               System.out.println("exiting...");
               System.exit(0);

           } else {
               System.out.println("Operation not recognized. Please choose from the available list.");
           }
       } // end while-loop
   } // end main
} // end driver

Facebook.java

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class Facebook implements Serializable {

   /**
   *
   */
   private static final long serialVersionUID = 1L;
   transient Scanner keyboard = new Scanner(System.in);
   private Map<String, FacebookUser> users;

   public Facebook() {
       users = new HashMap<String, FacebookUser>();

   }

   // prints users
   public void printUsers() {
       for (String key : users.keySet()) {
           System.out.println(users.get(key));
       }
   }

   // adds a user
   public void addUser() {

       System.out.println("Please enter a username.");
       String username = keyboard.nextLine();
       if (users.containsKey(username)) {
           System.out.println("that user exist");
       } else {
           System.out.println("Please enter a password.");
           String password = keyboard.nextLine();
           System.out.println("Please enter a password hint.");
           String passWordHint = keyboard.nextLine();
           FacebookUser facebookUser = new FacebookUser(username, password);
           facebookUser.setPasswordHint(passWordHint);
           users.put(username, facebookUser);
       }
   }

   // deletes a user
   public void deleteUser() {
       System.out.println("Please enter a username.");
       String username = keyboard.nextLine();
       if (users.containsKey(username)) {
           FacebookUser facebookUser = users.get(username);
           System.out.println("Please enter a password");
           String password = keyboard.nextLine();
           if (facebookUser.password.equals(password)) {
               users.remove(username);
               System.out.println("User Removed");
           }
       } else {
           System.out.println("That username does not exist");
       }
   }

   public void getPasswordHelp() {
       System.out.println("Please enter a username.");
       String username = keyboard.nextLine();
       if (users.containsKey(username)) {
           FacebookUser facebookUser = users.get(username);
           facebookUser.getPasswordHelp();
       } else {
           System.out.println("That user does not exist");
       }
   }

   public void friend() {
       System.out.println("Please enter a username.");
       String username = keyboard.nextLine();
       if (username != null && !users.containsKey(username)) {
           System.out.println("that user does not exist");
       } else {
           FacebookUser facebookUser = users.get(username);
           System.out.println("Please enter a password.");
           String password = keyboard.nextLine();
           if (facebookUser.password.equals(password)) {

               System.out.println("Please enter a friend's name");
               String friendName = keyboard.nextLine();
               if (friendName.equals(username)) {
                   System.out.println("You cannot friend yourself");
               } else {
                   FacebookUser friend = users.get(friendName);
                   facebookUser.friend(friend);
                   users.put(username, facebookUser);
               }
           }

       }
   }

   public void defriend(FacebookUser formerFriend) {
       System.out.println("Please enter a username.");
       String username = keyboard.nextLine();
       if (username != null && !users.containsKey(username)) {
           System.out.println("that user does not exist");
       } else {
           FacebookUser facebookUser = users.get(username);
           System.out.println("Please enter a password.");
           String password = keyboard.nextLine();
           if (facebookUser.password.equals(password)) {

               System.out.println("Please enter a friend's name");
               String friendName = keyboard.nextLine();
               if (friendName.equals(username)) {
                   System.out.println("You cannot de-friend yourself");
               } else {
                   FacebookUser friend = users.get(friendName);
                   facebookUser.defriend(friend);
               }
           }

       }
   }

   public void listFriends() {
       System.out.println("Please enter a username.");
       String username = keyboard.nextLine();
       if (username != null && !users.containsKey(username)) {
           System.out.println("that user does not exist");
       } else {
           FacebookUser facebookUser = users.get(username);
           System.out.println("Please enter a password.");
           String password = keyboard.nextLine();
           if (facebookUser.password.equals(password)) {
               System.out.println("Friends List:");
               facebookUser.getFriends();
           }

       }
   }

   public void getRecommendations() {
       System.out.println("Please enter a username.");
       String username = keyboard.nextLine();
       if (username != null && !users.containsKey(username)) {
           System.out.println("that user does not exist");
       } else {
           FacebookUser facebookUser = users.get(username);
           System.out.println("Please enter a password.");
           String password = keyboard.nextLine();
           if (facebookUser.password.equals(password)) {
               ArrayList<FacebookUser> recommendations = new ArrayList<FacebookUser>();
               for (FacebookUser f : facebookUser.friends) {
                   getRecommendations(f, recommendations);
               }

               if (!recommendations.isEmpty()) {

                   System.out.println("Recommendation friends List:");
                   for (FacebookUser u : recommendations) {
                       System.out.println(u);
                   }
               }
           }

       }
   }

   private void getRecommendations(FacebookUser user,
           ArrayList<FacebookUser> recommendations) {
       if (user != null && user.friends != null && !user.friends.isEmpty()) {
           for (FacebookUser friend : user.friends) {
               if (!recommendations.contains(friend)) {
                   recommendations.add(friend);
                   getRecommendations(friend, recommendations);
               }
           }
       }
   }

}

FacebookUser.java

import java.io.Serializable;
import java.util.ArrayList;

public class FacebookUser extends UserAccount implements
       Comparable<FacebookUser>, Cloneable, Serializable {

   /**
   *
   */
   private static final long serialVersionUID = 1L;
   protected String passwordHint;
   protected ArrayList<FacebookUser> friends;

   public FacebookUser(String username, String password) {
       super(username, password);
       friends = new ArrayList<FacebookUser>();
   }

   public void setPasswordHint(String hint) {
       this.passwordHint = hint;
   }

   public void friend(FacebookUser newFriend) {
       if (friends.contains(newFriend)) {
           System.out.println("That friend has already been added. ");
       } else {
           friends.add(newFriend);
       }
   }

   public void defriend(FacebookUser formerFriend) {
       if (!friends.contains(formerFriend)) {
           System.out.println("That friend has not been added. ");
       } else {
           friends.remove(formerFriend);
       }
   }

   public ArrayList<FacebookUser> getFriends() {
       ArrayList<FacebookUser> friendsCopy = new ArrayList<FacebookUser>();
       for (FacebookUser user : this.friends) {
           try {
               friendsCopy.add((FacebookUser) user.clone());
           } catch (CloneNotSupportedException cloneNotSupportedException) {
               cloneNotSupportedException.printStackTrace();
           }
       }
       for (int i = 0; i < friendsCopy.size(); i++) {
           System.out.println(friendsCopy.get(i));
       }
       return friendsCopy;
   }

   public int compareTo(FacebookUser o) {
       if (this.username.compareToIgnoreCase(o.username) != 0) {
           return this.username.compareToIgnoreCase(o.username);
       }

       return 0;
   }

   @Override
   public void getPasswordHelp() {
       setPasswordHint(passwordHint);
       System.out.println("Password Hint: " + passwordHint);

   }
}


UserAccount.java

import java.io.Serializable;

public abstract class UserAccount implements Serializable {

   /**
   *
   */
   private static final long serialVersionUID = 1L;
   protected String username;
   protected String password;
   protected boolean active; // indicates whether or not the account is
                               // currently active

   public UserAccount(String username, String password) {
       this.username = username;
       this.password = password;
       active = true;
   }

   public boolean checkPassword(String password) {
       boolean passwordMatch;
       if (password.equals(this.password)) {
           passwordMatch = true;
       } else {
           passwordMatch = false;
       }
       return passwordMatch;
   }

   public void deactivateAccount() {
       active = false;
   }

   @Override
   public int hashCode() {
       final int prime = 31;
       int result = 1;
       result = prime * result
               + ((username == null) ? 0 : username.hashCode());
       return result;
   }

   @Override
   public boolean equals(Object obj) {
       if (this == obj)
           return true;
       if (obj == null)
           return false;
       if (getClass() != obj.getClass())
           return false;
       UserAccount other = (UserAccount) obj;
       if (username == null) {
           if (other.username != null)
               return false;
       } else if (!username.equals(other.username))
           return false;
       return true;
   }

   @Override
   public String toString() {
       return "Username: " + username + " ";
   }

   public abstract void getPasswordHelp();

} // end UserAccount


Add a comment
Know the answer?
Add Answer to:
IN JAVA 04. Fourth Assignment – Facebook Friends We’ll continue with the Facebook application by enabling...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • need help in Java Now we’ll continue our project by writing a Facebook class that contains an ArrayList of Facebook user...

    need help in Java Now we’ll continue our project by writing a Facebook class that contains an ArrayList of Facebook user objects. The Facebook class should have methods to list all of the users (i.e. print out their usernames), add a user,delete a user, and get the password hint for a user You will also need to create a driver program. The driver should create an instance of the Facebook class and display a menu containing five options: list users...

  • 02. Second Assignment – The FacebookUser Class We’re going to make a small change to the...

    02. Second Assignment – The FacebookUser Class We’re going to make a small change to the UserAccount class from the last assignment by adding a new method: public abstract void getPasswordHelp(); This method is abstract because different types of user accounts may provide different types of help, such as providing a password hint that was entered by the user when the account was created or initiating a process to reset the password. Next we will create a subclass of UserAccount...

  • Need assistance with this problem. This is for a java class and using eclipse. For this...

    Need assistance with this problem. This is for a java class and using eclipse. For this assignment we’ll be doing problems 21.3 and 21.4 from your textbook. Problem 21.3 asks you to write a generic method that removes duplicate items from an ArrayList. This should be fairly straightforward. Problem 21.4 asks you to implement insertion sort within a generic method. Insertion sort is described in detail on pages 250-252 of your textbook. You can write your two methods in a...

  • This assignment shpuld be code in java. Thanks Overview In this assignment you will write a...

    This assignment shpuld be code in java. Thanks Overview In this assignment you will write a program that will model a pet store. The program will have a Pet class to model individual pets and the Assignment5 class will contain the main and act as the pet store. Users will be able to view the pets, make them age a year at a time, add a new pet, and adopt any of the pets. Note: From this point on, your...

  • In this assignment, you will create an application that holds a list of contact information. You ...

    In this assignment, you will create an application that holds a list of contact information. You will be able to prompt the user for a new contact, which is added to the list. You can print the contact list at any time. You will also be able to save the contact list. MUST BE IN PYTHON FORMAT Create the folllowing objects: ContactsItem - attributes hold the values for the contact, including FirstName - 20 characters LastName - 20 characters Address...

  • In this assignment, you will create an application that holds a list of contact information. You...

    In this assignment, you will create an application that holds a list of contact information. You will be able to prompt the user for a new contact, which is added to the list. You can print the contact list at any time. You will also be able to save the contact list. Must Be In Python Format Create the following objects: ContactsItem - attributes hold the values for the contact, including FirstName - 20 characters LastName - 20 characters Address...

  • AA. Final Project - Improved JavaFX GUI Personal Lending Library Description: In this project we will...

    AA. Final Project - Improved JavaFX GUI Personal Lending Library Description: In this project we will improve our personal lending library tool by (1) adding the ability to delete items from the library, (2) creating a graphical user interface that shows the contents of the library and allows the user to add, delete, check out, or check in an item. (3) using a file to store the library contents so that they persist between program executions, and (4) removing the...

  • Java FX Application Purpose The purpose of this assignment is to get you familiar with the...

    Java FX Application Purpose The purpose of this assignment is to get you familiar with the basics of the JavaFX GUI interface components. This assignment will cover Labels, Fonts, Basic Images, and Layouts. You will use a StackPane and a BorderPane to construct the layout to the right. In addition you will use the Random class to randomly load an image when the application loads Introduction The application sets the root layout to a BorderPane. The BorderPane can be divided...

  • package _solution; /** This program demonstrates how numeric types and operators behave in Java Do Task...

    package _solution; /** This program demonstrates how numeric types and operators behave in Java Do Task #1 before adding Task#2 where indicated. */ public class NumericTypesOriginal { public static void main (String [] args) { //TASK #2 Create a Scanner object here //identifier declarations final int NUMBER = 2 ; // number of scores int score1 = 100; // first test score int score2 = 95; // second test score final int BOILING_IN_F = 212; // boiling temperature double fToC;...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT