Question

In: Computer Science

Step 4: Create a class called BabyNamesDatabase This class maintains an ArrayList of BabyName objects. Instance...

Step 4: Create a class called BabyNamesDatabase

This class maintains an ArrayList of BabyName objects.

Instance Variables

  • Declare an ArrayList of BabyName objects.

Constructor

  • public BabyNamesDatabase () - instantiate the ArrayList of BabyName objects. You will not insert the items yet. This method will be one line of code.

Mutator Methods

  • public void readBabyNameData(String filename) - open the provided filename given as input parameter, use a loop to read all the data in the file, create a BabyName object for each record and add it to the ArrayList. We are providing most of the code for this method. Look for the TO DO comments to complete the logic.

Background Information: Reading from a Text File

The data file contains baby name records from the U.S. Social Security Administration since 1880. The readBabyNameData() method reads four items that are separated by commas, passes them to the BabyName class constructor and adds the BabyName object to the ArrayList.

Sample record: Mary,F,7065,1880

public void readBabyNameData(String filename){

  

     // Read the full set of data from a text file

     try{

          // open the text file and use a Scanner to read the text

          FileInputStream fileByteStream = new FileInputStream(filename);

          Scanner scnr = new Scanner(fileByteStream);

          scnr.useDelimiter("[,\r\n]+");

          

          // keep reading as long as there is more data

          while(scnr.hasNext()) {

              

               // reads each element of the record

               String name = scnr.next();

               String gender = scnr.next();

               // TO DO: read the count and year

               int count = ;

               int year = ;

               // TO DO: assign true/false to boolean isFemale based on

               // the gender String

               boolean isFemale;

               // instantiates an object of the BabyName class

               BabyName babyName = new BabyName(name, isFemale, count, year);

               // TO DO: add to the ArrayList the babyName created above

              

          }

          fileByteStream.close();

     }

     catch(IOException e) {

          System.out.println("Failed to read the data file: " + filename);

     }

}

Accessor Methods

  • public int countAllNames () - return the number of baby names using one line of code.  
  • public int countAllGirls() – Use a for-each loop to search the full list and count the total number of girls born since 1880. This number will be much higher than just the number of girl names since each name represents hundreds, if not thousands, of newborn babies.
  • public int countAllBoys() – Use a for-each loop to search the full list and count the total number of boys since 1880. This number will be much higher than just the number of boy names since each name represents hundreds, if not thousands, of newborn babies.
  • public ArrayList <BabyName> searchForYear(int year) – Use a for-each loop to search the full list and return a new list of baby names that match the requested year (in the parameter). If there is no match for the year, the returned list will exist but have zero elements.
  • public BabyName mostPopularGirl(int year) – use a for-each loop to navigate the list of baby names and return the most popular girl name for that specific year. Return null if there are no baby names for the year entered as input parameter.
  • public BabyName mostPopularBoy(int year) – use a for-each loop to navigate the list of baby names and return the most popular boy name for that specific year. Return null if there are no baby names for the year entered as input parameter.
  • public ArrayList <BabyName> searchForName(String name) – Use a for-each loop to search the full list and return a new list of baby names that match the requested name (in the parameter). Spelling should match exactly but it is not case sensitive. For example, ‘Angie’, ‘angie’ and ‘ANGIE’ all match. Hint, check out the String method called equalsIgnoreCase(String str). If there are no matches for the name, the returned list will exist but have zero elements.

Step 5: Generate a Top Ten List

To generate a top ten list for a particular year your solution must be able to sort names in descending order by number of births. This requires changes to the BabyName and BabyNamesDatabase classes.

Changes to BabyName class

  • Add two words to the end of the class header (shown below). You will need to import a new java package for this to compile. This allows BabyName objects to be compared using compareTo() and therefore sorted.

public class BabyName implements Comparable{

  • Also, add the following method. This method allows two BabyName objects to be compared with respect to the number of births.

IMPORTANT NOTE: For the compareTo method below, we are assuming that the name of the instance variable for the number of births is count.

               public int compareTo(Object other){

     BabyName b = (BabyName) other;

     return (b.count – count);

   }

Changes to BabyNamesDatabase class

NOTE: Sorting an ArrayList, called tempList, can be performed with one line of code:

   Collections.sort(tempList);

  • Change the searchForYear method. Use the instruction shown above to sort the ArrayList of BabyName objects that this method returns before returning it.
  • public ArrayList <BabyName> topTenNames(int year) – search the full list and return a new list of the ten most popular baby names in a given year entered as input parameter. The returned list will exist but have zero elements if there are no records for the specified year. Otherwise, it will have ten names. Avoid duplicating code by calling the searchForYear method to first select all names in the year.  

Once you have the list of all names in the year sorted in descending order by the count of births, you can do any of these three options to figure out the top ten baby names for that year

  • you can remove all items from the temporary list except the first ten before returning the result. Use a for loop that goes backwards if you want to use this option.
  • you may create another temporary list and add to this new list only the first 10 records from the list of all names in the year.
  • you may use the subList and removeAll methods of the ArrayList class. See Java API for documentation on how to use these two methods.

BABY NAME JAVA CODE

package pranam; // imported some imaginary package

import java.text.DecimalFormat; // imported Decimal Format

public class Babyname { // create class Babyname
   private static final String girls = null; // create string of girls (constant
   private static final String named = null;
   private static final String in = null;
   String name;
   boolean gender;
   int number_of_babies_given_that_name;
   int birth_year;
  
   public Babyname(String name, boolean gender,   
           int number_of_babies_given_that_name, int birth_year) { //defined a constructor
       super();
       this.name = name;
       this.gender = gender;
       this.number_of_babies_given_that_name = number_of_babies_given_that_name;
       this.birth_year = birth_year;
      
   }

   public String getName() { // Getters and setters for the functions
       return name;
   }

   public void setName(String name) {
       this.name = name;
   }

   public boolean isGender() {
       return gender;
   }

   public void setGender(boolean gender) {
       this.gender = gender;
   }

   public int getNumber_of_babies_given_that_name() {
       return number_of_babies_given_that_name;
   }

   public void setNumber_of_babies_given_that_name(
           int number_of_babies_given_that_name) {
       this.number_of_babies_given_that_name = number_of_babies_given_that_name;
   }

   public int getBirth_year() {
       return birth_year;
   }

   public void setBirth_year(int birth_year) {
       this.birth_year = birth_year;
   }
  
   public boolean isFemale(){ // generate the isFemale function
       if(gender=true)
           return true;
       else
           return false;
   }

   @Override
   public String toString() { // Generate the toString function
       DecimalFormat fmt = new DecimalFormat ("###,###,###");
      
      
       return " ["
               + number_of_babies_given_that_name + " " + "girls" +" "
               + "named" +" "+ name +" "+ "in" + ","+ birth_year + "]";
   }

}

Solutions

Expert Solution

=============================
JAVA PROGRAM
=============================
//////BabyName.JAVA
package PRANUM;
import java.text.DecimalFormat; // imported Decimal Format

//Class:BabyName
public class BabyName implements Comparable{ // create class Babyname
private static final String girls = null; // create string of girls (constant
private static final String named = null;
private static final String in = null;
String name;
boolean gender;
int number_of_babies_given_that_name;
int birth_year;
  
public BabyName(String name, boolean gender,   
int number_of_babies_given_that_name, int birth_year) { //defined a constructor
super();
this.name = name;
this.gender = gender;
this.number_of_babies_given_that_name = number_of_babies_given_that_name;
this.birth_year = birth_year;
  
}

public String getName() { // Getters and setters for the functions
return name;
}

public void setName(String name) {
this.name = name;
}

public boolean isGender() {
return gender;
}

public void setGender(boolean gender) {
this.gender = gender;
}

public int getNumber_of_babies_given_that_name() {
return number_of_babies_given_that_name;
}

public void setNumber_of_babies_given_that_name(
int number_of_babies_given_that_name) {
this.number_of_babies_given_that_name = number_of_babies_given_that_name;
}

public int getBirth_year() {
return birth_year;
}

public void setBirth_year(int birth_year) {
this.birth_year = birth_year;
}
  
public boolean isFemale(){ // generate the isFemale function
if(gender=true)
return true;
else
return false;
}

@Override
public String toString() { // Generate the toString function
DecimalFormat fmt = new DecimalFormat ("###,###,###");
return " ["
+ number_of_babies_given_that_name + " " + (gender?"girls":"boys") +" "
+ "named" +" "+ name +" "+ "in" + ","+ birth_year + "]";
}

@Override
public int compareTo(Object other) {
   BabyName b = (BabyName) other;
   int value =b.number_of_babies_given_that_name - this.number_of_babies_given_that_name;
   return value;
}

}


/////////////BabyNamesDatabase.JAVA
package PRANUM;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;

public class BabyNamesDatabase {
   private ArrayList<BabyName> babyNames = null;
  
   public BabyNamesDatabase (){
       babyNames = new ArrayList<BabyName>();
   }
  
   /**
   * return the number of baby names
   * @return
   */
   public int countAllNames(){
       return babyNames.size();
   }
   /**
   * count the total number of girls born since 1880.
   * This number will be much higher than just the number of girl names since
   * each name represents hundreds, if not thousands, of newborn babies
   * @return
   */
   public int countAllGirls(){
       int count = 0;
       for(BabyName bn: babyNames){
           if(bn.getBirth_year() >=1880 && bn.gender == true){//gender will be true for female as per logic
               count = count + bn.number_of_babies_given_that_name;
           }
       }
       return count;
   }
   /**
   * count the total number of boys born since 1880.
   * This number will be much higher than just the number of girl names since
   * each name represents hundreds, if not thousands, of newborn babies
   * @return
   */
   public int countAllBoys(){
       int count = 0;
       for(BabyName bn: babyNames){
           if(bn.getBirth_year() >=1880 && bn.gender == false){//gender will be false for male as per logic
               count = count + bn.number_of_babies_given_that_name;
           }
       }
       return count;
   }
   /**
   * The method will search the full list and return a new list of baby names that match
   * the requested year (in the parameter). If there is no match for the year,
   * the returned list will exist but have zero elements.
   * @param year
   * @return
   */
   public ArrayList<BabyName> searchForYear(int year) {
       ArrayList<BabyName> newListOfNames = new ArrayList<BabyName>();
       for(BabyName bn: babyNames){
           if(bn.getBirth_year()==year){
                   newListOfNames.add(bn);
           }
       }
       Collections.sort(newListOfNames);
       return newListOfNames;
   }
   /**
   * The method will navigate the list of baby names and return the most popular girl name for that specific year.
   * Return null if there are no baby names for the year entered as input parameter.
   * @param year
   * @return
   */
   public BabyName mostPopularGirl(int year){
       //get all babynames for the year in descending order of baby count
       ArrayList<BabyName> allNames = searchForYear(year);
       BabyName theBabyName = null;
       for(BabyName bn: allNames){
           if(bn.gender==true){//the first girl found in the list will be most popular as it has the highest count
               theBabyName = bn;
               break;
           }
       }
       return theBabyName;
   }
  
   /**
   * The method will navigate the list of baby names and return the most popular boy name for that specific year.
   * Return null if there are no baby names for the year entered as input parameter.
   * @param year
   * @return
   */
   public BabyName mostPopularBoy(int year){
       //get all babynames for the year in descending order of baby count
       ArrayList<BabyName> allNames = searchForYear(year);
       BabyName theBabyName = null;
       for(BabyName bn: allNames){
           if(bn.gender==false){//the first boy found in the list will be most popular as it has the highest count
               theBabyName = bn;
               break;
           }
       }
       return theBabyName;
   }
  
   /**
   * to search the full list and return a new list of baby names that match
   * the requested name (in the parameter). Spelling should match exactly but it is not case sensitive.
   * For example, ‘Angie’, ‘angie’ and ‘ANGIE’ all match.
   * If there are no matches for the name, the returned list will exist but have zero elements.
   * @param name
   * @return
   */
   public ArrayList <BabyName> searchForName(String name){
       ArrayList<BabyName> newBabyNames = new ArrayList<BabyName>();
       for(BabyName bn: babyNames){
           if(bn.getName().equalsIgnoreCase(name)){
               newBabyNames.add(bn);
           }
       }
       return newBabyNames;
   }
  
   /**
   * The method will search the full list and return a new list of the ten most popular
   * baby names in a given year entered as input parameter. The returned list will exist but
   * have zero elements if there are no records for the specified year. Otherwise, it will have ten names.
   * @param year
   * @return
   */
   public ArrayList <BabyName> topTenNames(int year) {
       ArrayList<BabyName> allNames = searchForYear(year);
       ArrayList<BabyName> top10List = new ArrayList<BabyName>();
       if(allNames!=null && !allNames.isEmpty()){
           for(BabyName bn: allNames){
               top10List.add(bn);
               if(top10List.size()==10)
                   break;
           }
       }
       return top10List;
   }
  
   /**
   * read and populate babyNames by reading from file
   * @param filename
   */
   public void readBabyNameData(String filename){
   // Read the full set of data from a text file
   try{
   // open the text file and use a Scanner to read the text
   FileInputStream fileByteStream = new FileInputStream(filename);
   Scanner scnr = new Scanner(fileByteStream);
   scnr.useDelimiter("[,\r\n]+");
   // keep reading as long as there is more data
   while(scnr.hasNext()) {
   // reads each element of the record
   String name = scnr.next();
   String gender = scnr.next();
   // TO DO: read the count and year
   int count = Integer.parseInt(scnr.next());
   int year = Integer.parseInt(scnr.next());
   // TO DO: assign true/false to boolean isFemale based on
   // the gender String
   boolean isFemale = gender.equals("F")?true:false;
   // instantiates an object of the BabyName class
   BabyName babyName = new BabyName(name, isFemale, count, year);
   // TO DO: add to the ArrayList the babyName created above   
   babyNames.add(babyName);

   }
   scnr.close();//scanner is closed
   fileByteStream.close();
   }catch(IOException e) {
   System.out.println("Failed to read the data file: " + filename);
   }

   }

}


///////////////TestBabyNames.JAVA
package PRANUM;

import java.util.ArrayList;
//tHIS IS THE TEST CLASS
public class TestBabyNames {
  
   public static void main(String[] args){
       String filename = "babynames.txt";
       BabyNamesDatabase bnd = new BabyNamesDatabase();
       bnd.readBabyNameData(filename);
       System.out.println("Total name Count = "+ bnd.countAllNames());
       System.out.println("Total Boy count = "+bnd.countAllBoys());
       System.out.println("Total Girl count = "+bnd.countAllGirls());
      
       System.out.println("Most popular Girl for the year 1880: ");
       System.out.println(bnd.mostPopularGirl(1880));
       System.out.println("Most popular Boy for the year 1880: ");
       System.out.println(bnd.mostPopularBoy(1880));
      
       System.out.println("All babies for year 1880 are:");
       ArrayList<BabyName> babies1 = bnd.searchForYear(1880);
       babies1.forEach(System.out::println);
      
       System.out.println("Babies with name Amy are:");
       ArrayList<BabyName> babies2 = bnd.searchForName("Amy");
       babies2.forEach(System.out::println);
      
       System.out.println("Top 10 babies for the year 1881 are:");
       ArrayList<BabyName> top10 = bnd.topTenNames(1881);
       top10.forEach(System.out::println);
      
   }

}


================================================
INPUT DATA (babynames.txt)
================================================
Mary,F,7065,1880
AMY,F,3256,1880
Samuel,M,9812,1880
Pablo,M,2110,1880
Kim,F,1925,1880
Peter,M,5463,1881
Michael,M,4545,1881
Rebeca,F,7878,1881
Jenifer,F,4625,1881
Robert,M,6597,1881
Thomas,M,989,1881
Joseph,M,1589,1881
Mili,F,1369,1881
Elisa,F,1598,1881
John,M,9845,1881
Mark,M,4512,1881
Amy,F,7712,1881
Sujan,F,3216,1881

================================================
OUTPUT
=================================================
Total name Count = 18
Total Boy count = 45462
Total Girl count = 38644
Most popular Girl for the year 1880:
[7065 girls named Mary in,1880]
Most popular Boy for the year 1880:
[9812 boys named Samuel in,1880]
All babies for year 1880 are:
[9812 boys named Samuel in,1880]
[7065 girls named Mary in,1880]
[3256 girls named AMY in,1880]
[2110 boys named Pablo in,1880]
[1925 girls named Kim in,1880]
Babies with name Amy are:
[3256 girls named AMY in,1880]
[7712 girls named Amy in,1881]
Top 10 babies for the year 1881 are:
[9845 boys named John in,1881]
[7878 girls named Rebeca in,1881]
[7712 girls named Amy in,1881]
[6597 boys named Robert in,1881]
[5463 boys named Peter in,1881]
[4625 girls named Jenifer in,1881]
[4545 boys named Michael in,1881]
[4512 boys named Mark in,1881]
[3216 girls named Sujan in,1881]
[1598 girls named Elisa in,1881]


Related Solutions

Using C# Create a class called Artist that contains 4 pieces of information as instance variables:...
Using C# Create a class called Artist that contains 4 pieces of information as instance variables: name (datatype string), specialization – i.e., music, pottery, literature, paintings (datatype string), number of art items (datatype int), country of birth (datatype string). Create a constructor that initializes the 4 instance variables. The Artist class must contain a property for each instance variable with get and set accessors. The property for number should verify that the Artist contributions is greater than zero. If a...
Create a class called Sphere. The class will contain the following    Instance data double radius...
Create a class called Sphere. The class will contain the following    Instance data double radius Methods Constructor with one parameter which will be used to set the radius instance data Getter and Setter for radius             Area - calculate the area of the sphere (4 * PI * radius * radius)             Volume - calculate and return the volume of the sphere (4/3 * PIE * radius * radius * radius) toString - returns a string with the...
IN JAVA PLEASE Create a class called Child with an instance data values: name and age....
IN JAVA PLEASE Create a class called Child with an instance data values: name and age. a. Define a constructor to accept and initialize instance data b. include setter and getter methods for instance data c. include a toString method that returns a one line description of the child
in Java, Create a class called EMPLOYEE that includes three instance variables – a first name...
in Java, Create a class called EMPLOYEE that includes three instance variables – a first name (type String), a last name (type String) and a monthly salary (double). Provide a constructor that initializes the three instance variables. Provide a set and a get method for each instance variable. If the monthly salary is not positive, do not set its value. Write a test app names EmployeeTest that demonstrates class EMLOYEE’s capabilities. Create two EMPLOYEE objects and display each object’s yearly...
You will generate a People class of object and load an ArrayList with person objects, then...
You will generate a People class of object and load an ArrayList with person objects, then report the contents of that ArrayList. To do so, you must perform the following: (30 pts.) A) (15/30 pts. (line break, 11 pt) ) - Create a class file “People.java” (which will generate People.class upon compile). People.java will have eight(8) methods to 1) read a .txt file ‘people.txt’ 2) generate: ▪ List of all students AND teachers ▪ List of all students OR teachers...
Create a class called Student. Include the following instance variables: name, address, phone, gpa Create all...
Create a class called Student. Include the following instance variables: name, address, phone, gpa Create all of the methods required for a standard user defined class: constructors, accessors, mutators, toString, equals Create the client for testing the Student class Create another class called CourseSection Include instance variables for: course name, days and times course meets (String), description of course, student a, student b, student c (all of type Student) Create all of the methods required for a standard user defined...
Create a class called Vehicle that includes four instance variables:      name, type,     tank size and...
Create a class called Vehicle that includes four instance variables:      name, type,     tank size and average petrol consumption. Provide 2 constructors, the first takes name and type as parameter, the second takes four parameters for the four instance variables. (2 pt) Provide also a method called distancePerTank that calculate the average distance that a vehicle can travel if the tank is full (multiplies the tank size by the average petrol consumption), then returns the value. (2 pt) Provide a...
Create a PoemDriver.java class with a main method. In the main method, create an ArrayList of...
Create a PoemDriver.java class with a main method. In the main method, create an ArrayList of Poem objects, read in the information from PoemInfo.txt and create Poem objects to populate the ArrayList. After all data from the file is read in and the Poem objects added to the ArrayList- print the contents of the ArrayList. Paste your PoemDriver.java text (CtrlC to copy, CtrlV to paste) into the open space before. You should not change Poem.java or PoemInfo.txt. Watch your time...
Task Create a class called Mixed. Objects of type Mixed will store and manage rational numbers...
Task Create a class called Mixed. Objects of type Mixed will store and manage rational numbers in a mixed number format (integer part and a fraction part). The class, along with the required operator overloads, should be written in the files mixed.h and mixed.cpp. Details and Requirements Finish Lab 2 by creating a Mixed class definition with constructor functions and some methods. The Mixed class should have public member functions Evaluate(), ToFraction(), and Simplify(). The Evaluate() function should return a...
(32%) Create a class of function objects called StartsWith that satisfies the following specification: when initialized...
(32%) Create a class of function objects called StartsWith that satisfies the following specification: when initialized with character c, an object of this class behaves as a unary predicate that determines if its string argument starts with c. For example, StartsWith(’a’) is a function object that can be used as a unary predicate to determine if a string starts with an a. So StartsWith(’a’)("alice") would return true but StartsWith(’a’)("bob") would return false. The function objects should return false when called...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT