Question

Exercise 1: Adding a Test Harness to the Person class To make it easier to test...

Exercise 1: Adding a Test Harness to the Person class

To make it easier to test code that you have written for a Java class you can add to that class a main method that acts as a "test harness". A test harness is a main method that includes calls to methods that you wish to test. For convention this main method is the last method of the class.

If you have a test harness, you do not need to have a separate application program in order to test your class: the test harness is part of the class you are testing. In this part of the Lab, you will get some experience in writing a test harness.

Open the SocialNetworking project that you created in Lab 1.

We have provided code for a test harness for the Person class, in the file PersonTestHarness.txt. It creates a Person object (this tests the constructor) and prints the result of invoking most of the methods of the class. Add this main method to your Person.java.

Run only Person.java; it will execute the test harness (main method).

Now add code to the test harness to test the equals method: it should print a message like "same friend" if two objects of the class Person are the same according to the equals method documentation (i.e. if they have the same first name and last name), or print "not same friend" if they are not the same. (Hint: you can use friend1 and friend2 to compare two objects of class Person that are not the same, but for thorough testing, you should also create a third Person object who has the same name as one of the first two.)

Run Person.java again to execute the changed test harness.

Make sure you show your results to the TA.

Exercise 2: Adding to the SocialNetwork Class

Add the following two methods to the SocialNetwork class:

getNumFriends(): it will return the number of friends in the list.

clearFriends(): it will remove all friends from the list. (Hint: this can be implemented with just one assignment statement. The SocialNetwork class has an instance variable called numFriends that holds the current number of persons in the list of friends. If you set this to 0 (zero), you do not need to clear out the array numFriends - why not?)

Add a test harness to SocialNetwork.java to test your new methods by doing the following. (Note that this is not a complete test of the class; it will just give you a start in using a test harness in the Lab. You can add more tests later if you wish.)

Create a SocialNetwork object (Hint: see page 40 of the Topic 1 lecture notes)

Add three friends to your social network

Print the contents of your list of friends

Test the getNumFriends method

Test the clearFriends method (how will you show that this worked?)

Make sure you show your results to the TA.

Exercise 3: Using Javadoc comments

Note that the existing comments in Person.java and SocialNetwork.java are Javadoc comments. (You should have read the Introduction to Javadoc document before this Lab.) Add Javadoc comments for the new methods you added to SocialNetwork.java in Exercise 2.

Set up Eclipse to generate documentation for the classes in this Lab, from your Javadoc comments:

Go to Project, Generate Javadoc, ...

For the Javadoc command, click on the Configure button and locate the "javadoc.exe" program. This will be in the "bin" directory of the Java Development Kit installation on the machine. This could for instance be C:\Program Files\Java\jdk1.5.0_03\bin\javadoc.exe

Check the project for which you want to generate the documentation.

Ensure that Public and Use Standard Doclet are selected, and Destination is the default (Z:\{your workspace}\{your project}\doc) and click Finish.

Javadoc generates a tree of html files which comprise the documentation for the program. You should see these in the Package Explorer in Eclipse under the doc directory. You can view them in Eclipse by double clicking (start with index.html).

Make sure you show your results to the TA.

Exercise 4: Using the SocialNetwork Class in an Application

You will now use the SocialNetwork class in an application program. Run the application MyFriends.java that is part of your SocialNetworking project from Lab 1. It is a simple application program that creates and prints a list of friends. (For simplicity, there is no file I/O in this application at present.)

Add statements to MyFriends to do the following:

Call the remove() method to remove one of the friends whose name is already in the list, and report whether or not the remove was successful. Make sure you include the name of the person you removed in the message to the user, for example: "Mickey Mouse was removed successfully."

Call the remove() method for a person whose name is not in the list of friends, and report whether or not the remove was successful.

Print the revised list of contacts.

persontestharness.txt

/**
 * test harness
 */

public static void main (String[] args) {
        // create a friend
        Person friend1 = new Person("Mickey", "Mouse", "");
        friend1.setEmail("[email protected]");
        System.out.println(friend1);

        // test accessor methods
        System.out.println(friend1.getName());
        System.out.println(friend1.getEmail());

        // create a friend without email
        Person friend2 = new Person("Minnie", "Mouse", "");
        System.out.println(friend2);

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

Below is your code: -

SocialNetwork.java

/**

* Class that represents a social network as a list of persons (friends or contacts)

* @author salil

*/

public class SocialNetwork {

private final int DEFAULT_MAX_FRIENDS = 10; // default size of array

/* Attribute declarations */

private Person[] friendList; // array of persons (list of friends)

private int numFriends; // current number of persons in list

/**

* Constructor creates person array of default size

*/

public SocialNetwork (){

friendList = new Person[DEFAULT_MAX_FRIENDS];

numFriends = 0;

}

/**

* Constructor creates person array of specified size

* @param max maximum size of array

*/

public SocialNetwork(int max){

friendList = new Person[max];

numFriends = 0;

}

/**

* add method adds a person to the list

* @param firstName first name

* @param lastName last name

* @param email email address

*/

public void add(String firstName, String lastName, String email){

// create a new Person objetc

Person friend = new Person(firstName, lastName, email);

// add it to the array of friends

// if array is not big enough, double its capacity automatically

if (numFriends == friendList.length)

expandCapacity();

// add reference to friend at first free spot in array

friendList[numFriends] = friend;

numFriends++;

}

/**

* remove method removes a specified friend from the list

* @param firstName first name of person to be removed

* @param lastName last name of person to be removed

* @return true if friend was removed successfully, false otherwise

*/

public boolean remove(String firstName, String lastName){

final int NOT_FOUND = -1;

int search = NOT_FOUND;

Person target = new Person(firstName, lastName, "");

// if list is empty, can't remove

if (numFriends == 0){

return false;

}

// search the list for the specified friend

for (int i = 0; i < numFriends && search == NOT_FOUND; i ++)

if (friendList[i].equals(target))

search = i;

// if not found, can't remove

if (search == NOT_FOUND)

return false;

// target person found, remove by replacing with last one in list

friendList[search] = friendList[numFriends - 1];

friendList[numFriends - 1] = null;

numFriends --;

return true;

}

/**

* toString method returns a string representation of all persons in the list

* @return first name and last name, email address of each person

*/

public String toString(){

String s = "";

for (int i = 0; i < numFriends; i++){

s = s + friendList[i].toString()+ "\n";

}

return s;

}

/**

* expandCapacity method is a helper method

* that creates a new array to store friends with twice the capacity

* of the existing one

*/

private void expandCapacity(){

Person[] largerList = new Person[friendList.length * 2];

for (int i = 0; i < friendList.length; i++)

largerList[i] = friendList[i];

friendList = largerList;

}

/**

* @return Method returns the integer value from the number of friends in the Person array

*/

public int getNumFriends() {

return numFriends;

}

/**

* Method sets the number of friends in SocialNetwork to 0; clears the array

*/

public void clearFriends() {

numFriends = 0;

}

/**

* test harness

*/

public static void main (String[] args) {

SocialNetwork socialNetwork = new SocialNetwork();

socialNetwork.add("John", "Doe", "[email protected]");

socialNetwork.add("Jack", "Doe", "[email protected]");

socialNetwork.add("Jerry", "Doe", "[email protected]");

System.out.println(socialNetwork);

System.out.println(socialNetwork.getNumFriends());

socialNetwork.clearFriends();

System.out.println(socialNetwork.getNumFriends());

}

}

Person.java

/**

* Class that represents a person with attributes name, email address

* @author salil

*

*/

public class Person {

/* Attribute declarations */

private String lastName; // last name

private String firstName; // first name

private String email; // email address

/**

* Constructor initializes the person's name and email address

*/

public Person(String firstName, String lastName, String email) {

this.firstName = firstName;

this.lastName = lastName;

this.email = email;

}

/**

* getName method returns the person's full name

* @return first name followed by last name, blank separated

*/

public String getName(){

return firstName + " " + lastName;

}

/**

* getEmail method returns the person's email address

* @return email address

*/

public String getEmail() {

return email;

}

/**

* setEmail method sets the person's email address

* @param email

*/

public void setEmail (String email) {

this.email = email;

}

/**

* equals method determines whether two persons have the same name

* @param other other Person object that this is compared to

* @return true of they have the same first name and last name, false otherwise

*/

public boolean equals(Person other){

if (this.firstName.equals(other.firstName)&& this.lastName.equals(other.lastName))

return true;

else

return false;

}

/**

* toString method returns a string representation of the person

* @return string with first name and last name, email address

*/

public String toString() {

String s = firstName + " " + lastName + "\t" + email;

return s;

}

/**

* test harness

*/

public static void main (String[] args) {

// create a friend

Person friend1 = new Person("Mickey", "Mouse", "");

friend1.setEmail("[email protected]");

System.out.println(friend1);

// test accessor methods

System.out.println(friend1.getName());

System.out.println(friend1.getEmail());

// create a friend without email

Person friend2 = new Person("Minnie", "Mouse", "");

System.out.println(friend2);

//third friend

Person friend3 = new Person("Mickey", "Mouse", "");

//test equals method

System.out.println(friend1.equals(friend2));

System.out.println(friend1.equals(friend3));

}

}

MyFriends.java

public class MyFriends {
  public static void main(String args[]) {

    SocialNetwork contacts = new SocialNetwork();

    contacts.add("Snoopy","Dog","[email protected]");
    contacts.add("Felix","Cat","[email protected]");
    contacts.add("Mickey","Mouse","[email protected]");
        
    contacts.remove("John", "Doe");

    System.out.println(contacts.toString());
    System.out.println("I have " + contacts.getNumFriends() + " friends in my list.");
    
    boolean check = contacts.remove("Mickey","Mouse");
    if(check==true) {
        System.out.println("Mickey Mouse was removed successfully.");
    }
    else {
        System.out.println("Mickey Mouse was not found.");
    }
    
    boolean check2 = contacts.remove("John","Doe");
    if(check2==true) {
        System.out.println("John Doe was removed successfully.");
    }
    else {
        System.out.println("John Doe was not found.");
    }
    
    System.out.println("I have " + contacts.getNumFriends() + " friends in my list.");
  }
}
Add a comment
Know the answer?
Add Answer to:
Exercise 1: Adding a Test Harness to the Person class To make it easier to test...
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
  • Please use C++,thank you! Write an AddressBook class that manages a collection of Person objects. Use the Person class developed in question 2. An AddressBook will allow a person to add, delete, o...

    Please use C++,thank you! Write an AddressBook class that manages a collection of Person objects. Use the Person class developed in question 2. An AddressBook will allow a person to add, delete, or search for a Perso n object in the address book The add method should add a person object to the address book. The delete method should remove the specified person object from the address book 0 .The search method that searches the address book for a specified...

  • The test harness is this. import java.util.ArrayList; public class ConcertTicketsTest { public static void main(String[...

    The test harness is this. import java.util.ArrayList; public class ConcertTicketsTest { public static void main(String[] args) { ArrayList listOfPeople = new ArrayList(); listOfPeople.add("Monica"); listOfPeople.add("Chandler"); listOfPeople.add("Rachel"); listOfPeople.add("Phobe"); listOfPeople.add("Joey"); listOfPeople.add("Ross"); listOfPeople.add("John"); listOfPeople.add("Daenerys"); listOfPeople.add("Arya"); listOfPeople.add("Sansa"); listOfPeople.add("Rob"); listOfPeople.add("Ned"); ConcertTickets concertTickets = new ConcertTickets(listOfPeople); concertTickets.removeFromLine("Ned"); concertTickets.removeFromLine("Ross"); concertTickets.insertInFront("Cersei"); System.out.println(concertTickets.printWaitlist()); System.out.println(concertTickets.listOfTicketHolders()); } } I do not have the sample output for this homework. Concepts Stacks Queues Linked List Programming Problems Stack - Implementation. You will be able to use the push, pop and peek of Stack concept....

  • USING JAVA, Class Design: Person The Person class is intended to be an abstract and simplified representation of a pers...

    USING JAVA, Class Design: Person The Person class is intended to be an abstract and simplified representation of a person. Each person will have an array of "friends" - which are other "Person" instances. Data to Store (2 Points) Name private instance variable with only private setter (2 Points) Friends private instance array with neither getter nor setter Actions Constructor o 1 Point) Take in as argument the name of the person (enforce invariants) o (1 Point) Initialize the array...

  • C++, Visual Studio (Optional-Extra Credit) Write an AddressBook class that manages a collection of Person objects....

    C++, Visual Studio (Optional-Extra Credit) Write an AddressBook class that manages a collection of Person objects. Use the Person class developed in question Lab 4 Question 2. An AddressBook will allow a person to add, delete, or search for a Person object in the address book 1. The add method should add a person object to the address book .The delete method should remove the specified person object from the address book .The search method that searches the address book...

  • Introduction In this lab, you will be working with three classes: Person, Student, and Roster. Person...

    Introduction In this lab, you will be working with three classes: Person, Student, and Roster. Person and Student represent individuals with a first and last name as String class variables, and Student has an additional int class variable that represents a ID number. The Roster class represents a group of people that are objects of either the Person or Student class. It contains an ArrayList. The Person class has been completed for you with class variables, a constructor, and a...

  • 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...

  • This Exercise contains two classes: ValidateTest and Validate. The Validate class uses try-catch and Regex expressions...

    This Exercise contains two classes: ValidateTest and Validate. The Validate class uses try-catch and Regex expressions in methods to test data passed to it from the ValidateTest program. Please watch the related videos listed in Canvas and finish creating the 3 remaining methods in the class. The regular expression you will need for a Phone number is: "^\\(?(\\d{3})\\)?[- ]?(\\d{3})[- ]?(\\d{4})$" and for an SSN: "^\\d{3}[- ]?\\d{2}[- ]?\\d{4}$" This exercise is meant to be done with the video listed in the...

  • 1/3 2/3 3/3 This programming assignment involves adding functionality to the SearchTreeset implementation found in the...

    1/3 2/3 3/3 This programming assignment involves adding functionality to the SearchTreeset implementation found in the SetMap project. Specifically you will edit the file util.SearchTreeSet and write Java-correct implementations of these methods * first pollFirst headset e lower The goal is to make these methods behave exactly like they would for a Java Treeset. Additional programming requirements the first, pollFirst, and lower methods should just take one or two passes down the tree. For a "well-balanced" tree, the time should...

  • import java.util.*; /** Description: This program determines the average of a list of (nonnegative) exam scores....

    import java.util.*; /** Description: This program determines the average of a list of (nonnegative) exam scores. Repeats for more exams until the user says to stop. Input: Numbers, sum, answer Output: Displays program description Displays instruction for user Displays average Algorithm: 1. START 2. Declare variables sum, numberOf Students, nextNumber, answer 3. Display welcome message and program description 4. DOWHILE user wants to continue 5. Display instructions on how to use the program 6. Inititalize sum and number of student...

  • Define a class named Employee . Derive this class from the class Person. An employee record...

    Define a class named Employee . Derive this class from the class Person. An employee record inherits an employee's name from the class Person. In addition, an employee record contains an annual salary (represented by a single value of type double), a hire date that gives the year hired (as a single value of type int), an identification number of type int, and a department of type String. Give your class a reasonable complement of constructors, accessors, mutators, an equals...

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
ADVERTISEMENT