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

40 points) Chapter 6: Programming Project #4 “Baby Names” a. Download the attach

ID: 3670883 • Letter: 4

Question

40 points) Chapter 6: Programming Project #4 “Baby Names”
a. Download the attached “BabyNames.java”, and “names.txt” file.
b. Modify the “BabyNames.java” so it will do the following:
i. The “names.txt” file contains data about popular baby names over the last 80 years in the United States (http://www.ssa.gov/OACT/babynames). Every 10 years, the data gives the 1000 most popular boy names and girl names for children born in the US. The data can be summarized in the following format:
...
Sam 99 131 168 236 278 380 467 408 466
Samantha 0 0 0 0 272 107 26 5 7
Samara 0 0 0 0 0 0 0 0 886
Samir 0 0 0 0 0 0 920 0 798
...
Each line has a name followed by the rank of that name in 1920, 1930, …, 2000 (9 numbers). A rank of 1 was the most popular name for that decade, while a rank of 907 was not that popular. A 0 means that the name was out of the 1000 popular names for that decade.
ii. Your program will give an introduction and then prompt the user for a name. Then it will read through the data file searching for that name. The search should be case-insensitive, meaning that you should find the name even if the file and the user use capital letters in different places. As an extreme example, SaMueL would match sAMUel.
iii. If your program finds the name, it should print out the statistics for that name onto screen. You are to reproduce this format exactly:
** Popularity of a baby name since year 1920 **
name? ada
1920: 154
1930: 196
CS 210 W. Li Assignment 6
1940: 244
1950: 331
1960: 445
1970: 627
1980: 962
1990: 0
2000: 0
Then, you need to save the statistics into a result file for that baby name. For the example above, the result file should be named as “Ada.txt”, which should contain contents in the following format exactly:
Ada,
1920: 154,
1930: 196,
1940: 244,
1950: 331,
1960: 445,
1970: 627,
1980: 962,
1990: 0,
2000: 0
iv. If the name is not in the data file, your program should generate a short message onto screen indicating the name was not found. You are to reproduce this format exactly:
** Popularity of a baby name since year 1920 **
name? kumar
name not found.
In this case, you should not generate the result file.
v. AFTER you successfully find the name, print out to screen and save to the result file, try drawing a graph for the ranks of that name over time. One example is
CS 210 W. Li Assignment 6
shown below. Of course, you can be creative here.
vi. Keep in mind, part v (the graph part) only worth 5 points. If you cannot get part v work, that’s ok – however, before submission you need to make sure your program still compiles and works for the previous parts. (Remember, if your code does not compile, you will lose a significant portion of your points!)
vii. Keep in mind, my computer directory is different from yours, so please DO NOT use absolute path for the files (e.g. c: emp.txt) - see Tip below. Otherwise, when I grade on my computer, it won’t work (then you will lose points!)
viii. For this assignment, you are limited to the language features in Chapters 1 through 6 of the textbook. In particular, do not use arrays on this assignment.
ix. Remember, your program will be graded both on “external correctness” and “internal design and style” (whether your source code follows the style guide).
c. Submit the final “BabyNames.java” file (DO NOT change the file name) online.
Tip: You need to have the file “names.txt” in the same directory as your java program is running from (i.e. the current directory). Otherwise, you will get “FileNotFoundException”. For people using IDE (like NetBeans or Eclipse), it’s probably not obvious where the current directory is. You can use the following code to find out:
String currentDir = System.getProperty("user.dir"); System.out.println(currentDir);
CS 210 W. Li Assignment 6
Run it, look at the output and figure out where the current directory is. Copy “names.txt” there, and move on!

Explanation / Answer

NameSurfer.java


import acm.program.*;
import java.awt.event.*;
import javax.swing.*;

public class NameSurfer extends Program implements NameSurferConstants{
  
/* Method: init() */
/**
* This method has the responsibility for reading in the data base
* and initializing the interactors at the bottom of the window.
*/
  
   public void init() {
      
       database = new NameSurferDataBase(NAMES_DATA_FILE);
      
       tf = new JTextField(10);
       tf.setActionCommand("Graph");
       tf.addActionListener(this);
      
        add(new JLabel("Name "),SOUTH);
        add(tf,SOUTH);
        add(new JButton("Graph"),SOUTH);
        add(new JButton("Clear"),SOUTH);
      
        graph = new NameSurferGraph();
        add(graph);
      
        addActionListeners();
   }
  
/* Method: actionPerformed(e) */
/**
* This class is responsible for detecting when the buttons are
* clicked, so you will have to define a method to respond to
* button actions.
*/
   public void actionPerformed(ActionEvent e) {
       if(e.getActionCommand().equals("Graph")){
          
           /* converting input in format stored in database */
           String entry = tf.getText().toLowerCase();
           entry = Character.toUpperCase(entry.charAt(0)) + entry.substring(1);
          
           graph.addEntry(database.findEntry(entry));
           tf.setText("");
       }else{
           graph.clear();
       }
   }
  
   private JTextField tf;
   private NameSurferGraph graph;
   private NameSurferDataBase database;
}


NameSurferConstants.java
/*
* File: NameSurferConstants.java
* ------------------------------
* This file declares several constants that are shared by the
* different modules in the NameSurfer application. Any class
* that implements this interface can use these constants.
*/

public interface NameSurferConstants {

/** The width of the application window */
   public static final int APPLICATION_WIDTH = 800;

/** The height of the application window */
   public static final int APPLICATION_HEIGHT = 600;

/** The name of the file containing the data */
   public static final String NAMES_DATA_FILE = "names-data.txt";

/** The first decade in the database */
   public static final int START_DECADE = 1900;

/** The number of decades */
   public static final int NDECADES = 11;

/** The maximum rank in the database */
   public static final int MAX_RANK = 1000;

/** The number of pixels to reserve at the top and bottom */
   public static final int GRAPH_MARGIN_SIZE = 20;

}

NameSurferDataBase.java

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;

/*
* File: NameSurferDataBase.java
* -----------------------------
* This class keeps track of the complete database of names.
* The constructor reads in the database from a file, and
* the only public method makes it possible to look up a
* name and get back the corresponding NameSurferEntry.
* Names are matched independent of case, so that "Eric"
* and "ERIC" are the same names.
*/

public class NameSurferDataBase {
  
/* Constructor: NameSurferDataBase(filename) */
/**
* Creates a new NameSurferDataBase and initializes it using the
* data in the specified file. The constructor throws an error
* exception if the requested file does not exist or if an error
* occurs as the file is being read.
*/
   public NameSurferDataBase(String filename) {
  
       inventory = new HashMap<String,NameSurferEntry>();
       try{
           BufferedReader rd = new BufferedReader(new FileReader(filename));
           while(true){
               String line = rd.readLine();
               if(line == null) break;
               NameSurferEntry entry = new NameSurferEntry(line);
               inventory.put(entry.getName(), entry);
           }
       }
       catch(IOException e){
           //ignore
       }
   }
  
/* Method: findEntry(name) */
/**
* Returns the NameSurferEntry associated with this name, if one
* exists. If the name does not appear in the database, this
* method returns null.
*/
   public NameSurferEntry findEntry(String name) {
       return inventory.get(name);
   }
  
   private Map<String,NameSurferEntry> inventory;
}


NameSurferEntry.java
/*
* File: NameSurferEntry.java
* --------------------------
* This class represents a single entry in the database. Each
* NameSurferEntry contains a name and a list giving the popularity
* of that name for each decade stretching back to 1900.
*/

import java.util.*;

public class NameSurferEntry implements NameSurferConstants {

/* Constructor: NameSurferEntry(line) */
/**
* Creates a new NameSurferEntry from a data line as it appears
* in the data file. Each line begins with the name, which is
* followed by integers giving the rank of that name for each
* decade.
*/
   public NameSurferEntry(String line) {
       parseLine(line);
   }
  
   private void parseLine(String line){
       StringTokenizer token = new StringTokenizer(line);
       name = token.nextToken();
       rank = new int[NDECADES];
      
       for(int i=0;i<NDECADES;i++){
           rank[i] = Integer.parseInt(token.nextToken());
       }
   }

/* Method: getName() */
/**
* Returns the name associated with this entry.
*/
   public String getName() {
       return name;
   }

/* Method: getRank(decade) */
/**
* Returns the rank associated with an entry for a particular
* decade. The decade value is an integer indicating how many
* decades have passed since the first year in the database,
* which is given by the constant START_DECADE. If a name does
* not appear in a decade, the rank value is 0.
*/
   public int[] getRank() {
       return rank;
   }

/* Method: toString() */
/**
* Returns a string that makes it easy to see the value of a
* NameSurferEntry.
*/
   public String toString() {
       String information = name+" [";
       for(int i =0;i<NDECADES-1;i++){
           information = information+rank[i]+" ";
       }
       information =information+rank[10]+"]";
       return information;
   }
  
   private String name;
   private int[] rank;
}


NameSurferGraph.java

/*
* File: NameSurferGraph.java
* ---------------------------
* This class represents the canvas on which the graph of
* names is drawn. This class is responsible for updating
* (redrawing) the graphs whenever the list of entries changes or the window is resized.
*/

import acm.graphics.*;
import java.awt.event.*;
import java.util.*;
import java.awt.*;

public class NameSurferGraph extends GCanvas
   implements NameSurferConstants, ComponentListener{

   /**
   * Creates a new NameSurferGraph object that displays the data.
   */
  
   public NameSurferGraph() {
       entries = new ArrayList<NameSurferEntry>();
       addComponentListener(this);
   }
  
   private void drawBackground(){
       int width = getWidth()/NDECADES;
       int height = getHeight();
      
       for(int i=0;i<NDECADES;i++){
           add(new GLine(i*width,0,i*width,height));
           GLabel label = new GLabel(""+(START_DECADE+i*10)+"");
           add(label,i*width,height-GRAPH_MARGIN_SIZE+label.getAscent());
       }
       add(new GLine(0,GRAPH_MARGIN_SIZE,getWidth(),GRAPH_MARGIN_SIZE));
       add(new GLine(0,height-GRAPH_MARGIN_SIZE,getWidth(),height-GRAPH_MARGIN_SIZE));
      
   }
  
   private void drawGraphForEntry(NameSurferEntry entry){
       Color color = getColor();
       int[] rank = entry.getRank();
       int width = getWidth()/NDECADES;
       double height = getHeight()-2*GRAPH_MARGIN_SIZE;
      
       for(int i=0;i<NDECADES-1;i++){
          
           int x1 = i*width;
           int x2 = (i+1)*width;
          
           double y1 = (rank[i]*(height/MAX_RANK))+GRAPH_MARGIN_SIZE;
           double y2 = (rank[i+1]*(height/MAX_RANK))+GRAPH_MARGIN_SIZE;
          
           String rankString;
          
           if(rank[i+1] == 0){
               y2 = height+GRAPH_MARGIN_SIZE;
           }
          
           if(rank[i] == 0){
               rankString = "*";
               y1 = height+GRAPH_MARGIN_SIZE;
              
           }else{
               rankString = String.valueOf(rank[i]);
           }
          
           GLine line = new GLine(x1,y1,x2,y2);
           line.setColor(color);
           add(line);
          
           GLabel label = new GLabel(entry.getName()+" "+ rankString);
           label.setColor(color);
           add(label,x1,y1);
          
           if(i==9){
               if(rank[i+1] == 0){
                   rankString = "*";
                   y2 = height+GRAPH_MARGIN_SIZE;
                  
               }else{
                   rankString = String.valueOf(rank[i+1]);
               }
              
               GLabel lastLabel = new GLabel(entry.getName()+" "+ rankString);
               lastLabel.setColor(color);
               add(lastLabel,x2,y2);
           }

       }
      
      
   }
  
   private Color getColor(){
       Color color = Color.black;
       switch(count%4){
          case 0 : color = Color.RED;
                  break;
          case 1 : color = Color.blue;
                  break;
          case 2 : color = Color.MAGENTA;
                  break;
          case 3 : color = Color.orange;
                  break;
         
       }
       return color;
   }
  
   /**
   * Clears the list of name surfer entries stored inside this class.
   */
   public void clear() {
       count = 0;
       entries.clear();
       update();
   }
  
   /* Method: addEntry(entry) */
   /**
   * Adds a new NameSurferEntry to the list of entries on the display.
   * Note that this method does not actually draw the graph, but
   * simply stores the entry; the graph is drawn by calling update.
   */
   public void addEntry(NameSurferEntry entry) {
       if(entry!=null && !entries.contains(entry)){
           count++;
           entries.add(entry);
           drawGraphForEntry(entry);
       }
   }
  
   /**
   * Updates the display image by deleting all the graphical objects
   * from the canvas and then reassembling the display according to
   * the list of entries. Your application must call update after
   * calling either clear or addEntry; update is also called whenever
   * the size of the canvas changes.
   */
   public void update() {
       count = 0;
       removeAll();
       drawBackground();
       for(int i=0;i<entries.size();i++){
           count++;
           drawGraphForEntry(entries.get(i));
       }
   }
  
  
   /* Implementation of the ComponentListener interface */
   public void componentHidden(ComponentEvent e) { }
   public void componentMoved(ComponentEvent e) { }
   public void componentResized(ComponentEvent e) { update(); }
   public void componentShown(ComponentEvent e) { }
  
   private ArrayList<NameSurferEntry> entries;
   private int count = 0;
}

names-data.txt
A 83 140 228 286 426 612 486 577 836 0 0
Aaliyah 0 0 0 0 0 0 0 0 0 380 215
Aaron 193 208 218 274 279 232 132 36 32 31 41
Abagail 0 0 0 0 0 0 0 0 0 0 958
Abbey 0 0 0 0 0 0 0 0 537 451 428
Abbie 431 552 742 924 0 0 0 0 752 644 601
Abbigail 0 0 0 0 0 0 0 0 0 953 562
Abby 0 0 0 0 0 906 782 548 233 211 209
Abdiel 0 0 0 0 0 0 0 0 0 925 721
Abdul 0 0 0 0 0 0 0 903 0 0 0
Abdullah 0 0 0 0 0 0 0 0 0 1000 863
Abe 248 328 532 764 733 0 0 0 0 0 0
Abel 664 613 626 575 542 491 497 422 381 385 354
Abigail 0 0 0 0 854 654 615 317 150 50 14
Abigale 0 0 0 0 0 0 0 0 0 0 959

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote