Question

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 called FacebookUser. The FacebookUser class needs to have the following fields and methods in addition to what is in UserAccount:

Fields:

String passwordHint

ArrayList<FacebookUser> friends

Methods:

void setPasswordHint(String hint) void friend(FacebookUser newFriend) void defriend(FacebookUser formerFriend) ArrayList<FacebookUser> getFriends()

The friend method should add the FacebookUser argument to the friends ArrayList (if that FacebookUser is already in the friends list, display an error message), and the defriend method should remove the FacebookUser argument from that ArrayList (if that FacebookUser is not in the friends list, display an error message). The getFriends method should return a copy of this user’s friends – create a new ArrayList with the same FacebookUsers in it as this user’s friends. Do not return the friends ArrayList directly, since this violates the principle of encapsulation. The getPasswordHelp method should display the passwordHint. The FacebookUser class should also implement the Comparable interface. FacebookUsers should be sorted alphabetically by username, ignoring capitalization. (Hint: notice that the toString method returns the username of the UserAccount.) Finally, write a driver program that creates several FacebookUsers and demonstrates the user of the setPasswordHint, friend, defriend, getFriends, and getPasswordHelp methods. Also, put the FacebookUser objects into an ArrayList, sort them (see the jar file for this topic for help on this), and print them out in sorted order.

You will be graded according to the following rubric (each item is worth one point):

  • The UserAccount class is abstract and has the requested fields and methods
  • The only abstract method is the getPasswordHelp method
  • The FacebookUser class extends UserAccount
  • FacebookUser has a friends ArrayList and methods to add, remove, and display the friends
  • FacebookUser implements Comparable and sorts alphabetically on username, ignoring capitalization
  • FacebookUser has a passwordHint that can be set through a method and is displayed by the getPasswordHelp method
  • The driver program creates a list of FacebookUsers
  • The driver program sorts and displays the lists of FacebookUsers
  • The driver program exercises the setPasswordHint, friend, defriend, getFriends, and getPasswordHelp methods
  • The program compiles and runs and the program is clearly written and follows standard coding conventions
  • 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.

Here is my code

package calculator;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;


public class Calculator extends Application {
  
@Override
public void start(Stage stage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("FXMLDocument.fxml"));
  
Scene scene = new Scene(root);
  
stage.setScene(scene);
stage.show();
}

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
  
}


package calculator;

import java.net.URL;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;


public class FXMLDocumentController implements Initializable {

private Double curr_num, end_res;
private String curr_operation;
Boolean res_oper=false;
@FXML
private TextField textToDisplay;

@Override
public void initialize(URL url, ResourceBundle rb) {

}

@FXML
private void handleDigitAction(ActionEvent event) {
if(res_oper){
textToDisplay.clear();
res_oper=false;
}
String digit = ((Button) event.getSource()).getText();
String oldText = textToDisplay.getText();
String newText = oldText + digit;
textToDisplay.setText(newText);
}

@FXML
private void handleOperationAction(ActionEvent event) {
String text = textToDisplay.getText();
Double digit = Double.parseDouble(text);
curr_num = digit;
curr_operation = ((Button) event.getSource()).getText();
textToDisplay.setText(curr_num + curr_operation);

}

@FXML
private void handleEqualOperation(ActionEvent event) {
Double val1,val2,res;
String val = textToDisplay.getText();
System.out.println(val);
if (val.contains("-")) {
String[] digits = val.split("-");
String digit1 = digits[0];
String digit2 = digits[1];
val1=Double.parseDouble(digit1);
val2=Double.parseDouble(digit2);
res=val1+val2;
textToDisplay.setText(res.toString());
}else if(val.contains("/")){
String[] digits = val.split("/");
String digit1 = digits[0];
String digit2 = digits[1];
val1=Double.parseDouble(digit1);
val2=Double.parseDouble(digit2);
res=val1-val2;
textToDisplay.setText(res.toString());
}else if(val.contains("X")){
String[] digits = val.split("X");
String digit1 = digits[0];
String digit2 = digits[1];
val1=Double.parseDouble(digit1);
val2=Double.parseDouble(digit2);
res=val1/val2;
textToDisplay.setText(res.toString());
}else if(val.contains("+")){
String[] digits = val.split("\\+");
String digit1 = digits[0];
String digit2 = digits[1];
val1=Double.parseDouble(digit1);
val2=Double.parseDouble(digit2);
res=val1*val2;
textToDisplay.setText(res.toString());
}
res_oper=true;

}

@FXML
private void handleClearAction(ActionEvent event) {
textToDisplay.clear();
}

@FXML
private void handleBackspaceAction(ActionEvent event) {
StringBuffer sb = new StringBuffer(textToDisplay.getText());
sb = sb.deleteCharAt(textToDisplay.getText().length()-1);
textToDisplay.setText(sb.toString());

}

}

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

DriverProgram.java

import java.util.ArrayList;
import java.util.Collections;

public class DriverProgram {

   public static void main(String[] args) {
       FacebookUser user1 = new FacebookUser("Walter White", "pa55");
       FacebookUser user2 = new FacebookUser("jesse Pinkman", "password");
       FacebookUser user3 = new FacebookUser("Daryl Dixon", "pas5");
       FacebookUser user4 = new FacebookUser("rick Grimes", "12345");
       System.out.println("\n");
      
       // create arrayList of FacebookUser then sort alphabetically ignoring case
       ArrayList<FacebookUser> users = new ArrayList<>();
       users.add(user1);
       users.add(user2);
       users.add(user3);
       users.add(user4);

       System.out.println("Users: ");
       for (FacebookUser faceBookUser : users) {
           System.out.println("\t" + faceBookUser);
       }

       System.out.println("\nSorting Users...\n");

       Collections.sort(users);

       System.out.println("Users: ");
       for (FacebookUser faceBookUser : users) {
           System.out.println("\t" + faceBookUser);
       }

       System.out.println("\n");
      
       // test setPasswordHint and getPasswordHelp methods
       user1.setPasswordHint("Thou shalt not pass");
       user1.getPasswordHelp();
       System.out.println(" ");
       user1.setPasswordHint("pwerd");
       user1.getPasswordHelp();
      
       //test friend method
       System.out.print("\n");
       System.out.println("***Test friend method***");
       user1.friend(user4);
       user1.friend(user3);
       user1.friend(user3);
       user1.friend(user2);
      
       //test defriend method
       System.out.print("\n");
       System.out.println("***Test defriend method***");
       user1.defriend(user2);
       user1.defriend(user2);

      
       //test getFriend method
       System.out.print("\n");
       System.out.println("***Test getFriend method***");
       user1.getFriends();


   }

}

FacebookUser.java

import java.util.ArrayList;

public class FacebookUser extends UserAccount implements
       Comparable<FacebookUser>, Cloneable {
   private String passwordHint;
   private 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;
   }

   @Override
   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:\n" + passwordHint);

   }
}

UserAccount.java

public abstract class UserAccount {

   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:
02. Second Assignment – The FacebookUser Class We’re going to make a small change to the...
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
  • The following is the class definition for Multiplier. This class has five (5) members: two private...

    The following is the class definition for Multiplier. This class has five (5) members: two private instance variables two private methods one public method this is only public method for the class it calls other two private methods import java.util.*; //We need to use Scanner & Random in this package public class Multiplier {        private int answer; //for holding the correct answer        private Random randomNumbers = new Random(); //for creating random numbers        //ask the user to work...

  • Intro to Java - Assignment JAVA ASSIGNMENT 13 - Object Methods During Event Handling Assignment 13...

    Intro to Java - Assignment JAVA ASSIGNMENT 13 - Object Methods During Event Handling Assignment 13 Assignment 13 Preparation This assignment will focus on the use of object methods during event handling. Assignment 13 Assignment 13 Submission Follow the directions below to submit Assignment 13: This assignment will be a modification of the Assignment 12 program (see EncryptionApplication11.java below). Replace the use of String concatenation operations in the methods with StringBuilder or StringBuffer objects and their methods. EncryptTextMethods.java ====================== package...

  • Written in Java I have an error in the accountFormCheck block can i get help to...

    Written in Java I have an error in the accountFormCheck block can i get help to fix it please. Java code is below. I keep getting an exception error when debugging it as well Collector.java package userCreation; import java.io.IOException; import java.net.URL; import java.util.ResourceBundle; import java.util.regex.Matcher; import java.util.regex.Pattern; import javafx.event.ActionEvent; import javafx.fxml.*; import javafx.scene.*; import javafx.scene.control.*; import javafx.scene.text.Text; import javafx.stage.*; public class Controller implements Initializable{ @FXML private PasswordField Password_text; @FXML private PasswordField Confirm_text; @FXML private TextField FirstName_text; @FXML private TextField LastName_text;...

  • Java: In this assignment, you will create an accumulator accumulator-calculator that displays a sad face “...

    Java: In this assignment, you will create an accumulator accumulator-calculator that displays a sad face “ :-( “ whenever the number displayed by the calculator is negative and a happy face “ :-) ” whenever the number displayed is positive. The calculator responds to the following commands: num + , num - , num * , num / and C ( Clear ). After initial run, if the user clicks 8 and then presses the “+” button for example, the...

  • For this question you will need to complete the methods to create a JavaFX GUI application...

    For this question you will need to complete the methods to create a JavaFX GUI application that implements two String analysis algorithms. Each algorithm is activated when its associated button is pressed. They both take their input from the text typed by the user in a TextField and they both display their output via a Text component at the bottom of the GUI, which is initialized to “Choose a string methods as indicated in the partially completed class shown after...

  • In the USIntsArrayList Class, implement the USIntsArrayListInterface Interface (which is really just the UnSortedInts Class without...

    In the USIntsArrayList Class, implement the USIntsArrayListInterface Interface (which is really just the UnSortedInts Class without the logic. All you are doing in this class is providing the same functionality as UnSortedInts, but using an ArrayList to hold the data. Document appropriately Thank you, package arrayalgorithms; import java.util.ArrayList; /** * Title UnSorted Ints stored in an Array List * Description: Implement all the functionality of the UnSortedInts * class using an ArrayList * @author Khalil Tantouri */ public class USIntsArrayList...

  • Given a class called Student and a class called Course that contains an ArrayList of Student....

    Given a class called Student and a class called Course that contains an ArrayList of Student. Write a method called getDeansList() as described below. Refer to Student.java below to learn what methods are available. I will paste both of the simple .JAVA codes below COURSE.JAVA import java.util.*; import java.io.*; /****************************************************** * A list of students in a course *****************************************************/ public class Course{     /** collection of Students */     private ArrayList<Student> roster; /***************************************************** Constructor for objects of class Course *****************************************************/...

  • Prompt: In this stepping stone lab assignment, you will build a Recipe class, getting user input...

    Prompt: In this stepping stone lab assignment, you will build a Recipe class, getting user input to collect the recipe name and serving size, using the ingredient entry code from Stepping Stone Lab Four to add ingredients to the recipe, and calculating the calories per serving. Additionally, you will build your first custom method to print the recipe to the screen. Specifically, you will need to create the following:  The instance variables for the class (recipeName, serving size, and...

  • How to solve and code the following requirements (below) using the JAVA program? 1. Modify the...

    How to solve and code the following requirements (below) using the JAVA program? 1. Modify the FoodProduct Class to implement Edible, add the @Overrride before any methods that were there (get/set methods) that are also in the Edible interface. 2. Modify the CleaningProduct Class to implement Chemical, add the @Overrride before any methods that were there (get/set methods) that are also in the Chemical interface. 3. Create main class to read products from a file, instantiate them, load them into...

  • Modify the JavaFX TipCalculator application program to allow the user to enter the number of persons...

    Modify the JavaFX TipCalculator application program to allow the user to enter the number of persons in the party through a text field. Calculate and display the amount owed by each person in the party if the bill is to be split evenly among the party members. /////////// TipCalculatorController.java: import java.math.BigDecimal; import java.math.RoundingMode; import java.text.NumberFormat; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.scene.control.Label; import javafx.scene.control.Slider; import javafx.scene.control.TextField; public class TipCalculatorController { // formatters for currency and percentages private...

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