cs106a – Assignment #6 – Task #3

The complete specification of assignment #6 can be found as part of the stream at iTunes.

Implement the NameSurferDataBase class

The next step in the process is to implement the NameSurferDataBase class, which
contains two public entries:

  • A constructor that takes the name of a data file and uses that to read in the entire set of data from the file into internal data structures that allow the class to keep track of all the records as a database.
  • A findEntry method that takes a name, looks it up in the stored database, and returns the NameSurferEntry for that name, or null if that name does not appear.

The code for this part of the assignment is not particularly difficult. The challenging part lies in figuring out how you want to represent the data so that you can implement the findEntry method as simply and as efficiently as possible.
To test this part of the program, you can add a line of code or two to the NameSurfer program so that it creates the NameSurferDataBase and then change the code for the button handlers so that clicking the Graph button looks up the current name in the data base and then displays the corresponding entry (using its toString method).


Start by creating a map as database using the name string as key and holding the name-surfer entry as value:

	private TreeMap<String,NameSurferEntry> data = new TreeMap<String,NameSurferEntry>();

Load the file und scan it feeding each line to the name-server-entry class. Put the returned object into the database using the lowercase name as key:

	public NameSurferDataBase(String filename) {
		File file = new File(filename);
		try {
			Scanner scanner = new Scanner(new FileReader(file));
			while (scanner.hasNextLine()) {
				NameSurferEntry entry = new NameSurferEntry(scanner.nextLine());
				String name = entry.getName().toLowerCase();
				if (!name.equals("error"))
					data.put(name, entry);
			}
			scanner.close();
		} catch (IOException ex) {
			// don't care do nothing
		}
	}

Because the map is already optimized to retrieve values for certain keys, just return the value for the given lowercase name:

	public NameSurferEntry findEntry(String name) {
		return data.get(name.toLowerCase());
	}

Create a new instance variable in the main class holding the database, and instantiate it:

        private NameSurferDataBase dataBase;

	public void init() {
		dataBase = new NameSurferDataBase(NAMES_DATA_FILE);
                ....
        }

To test the assignment adjust the actionPerformed() method:

println("Graph: \"" + dataBase.findEntry(nameField.getText()) + "\"");

The code for this assignment is available on github.

Facebooktwittergoogle_plusredditpinterestlinkedintumblrmailFacebooktwittergoogle_plusredditpinterestlinkedintumblrmail

Flattr this!

Leave a Reply

Your email address will not be published. Required fields are marked *