CS46B Lab 1

Copyright © Cay S. Horstmann 2010-2015 Creative Commons License
This work is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 United States License.

Modified by:

Instructions

Working in Pairs

Objectives

Learning Outcomes

A. Install the Virtual Machine

For this lab you will install Virtual Box and a Lubuntu virtual machine. You have to use the VM in the labs. If you chose to use something else for your homework, we will never know, but you are on your own to do so. Only the VM is supported in this class. If you are serious about being a CS/SE major, being able to use a VM and Linux is a must.

  1. The virtuall machine already has Eclipse(and other software) installed. If you don't have the virtual machine installed, install VirtualBox and ask the lab instructor to give you the virtual machine on a USB stick. (It is too large to download during the lab.) Copy it to your Downloads directory and then follow these instructions.

B. Making a Project

  1. Start Eclipse. If you installed it yourself, you should know how to do that. If you have the virtual machine installed, launch it, open a terminal window (Ctrl+Alt+T), and type
    eclipse/eclipse
  2. To create a new project, select FileNewProject...Java Project from the menu bar.
  3. In the next dialog, name the project Lab1.
  4. Now you are faced with an important decision. If you do not have existing source code, then you can use the default location. In real life, that almost never happens, because you don't usually start from scratch, with no code. So, we'll practice the more common situation where there is already some source code that you want to enhance. Go ahead and uncheck the “Use default location” check box.
  5. Next, make a directory cs46b inside your home directory, and a subdirectory labs. If you use the virtual machine, open a terminal window (Ctrl + Alt + T) and enter this command:
    mkdir -p ~/cs46b/labs
    
  6. Download this code and unzip it into the labs directory so that you have a directory path home directory/cs46b/labs/lab1. If you use the virtual machine, do the download in the browser of the virtual machine, then open a terminal window and enter these commands:
    cd ~/cs46b/labs
    jar xvf ~/Downloads/lab1.zip
    
  7. Now go back to Eclipse. Use the Browse button in Eclipse to navigate to the cs46b/labs/lab1 directory. (Be careful not to navigate to the src subdirectory.)
  8. Hit the Finish button. Now you have successfully created a Java project from an existing set of files.

If you had trouble in this step, be sure to ask the lab instructor to look over what you have been doing.

C. Overriding a Method in the AddressBook Interface

  1. In the Package Explorer, open lab1 → src → (default package). You will see .java files you copied
  2. Notice the red "X" on ArrayListAddressBook.java. That means the code did not compile. The red X's show which statements contain syntax errors.
  3. Double click ArrayListAddressBook.java, and it will open in the edit window
  4. What is the first error in the ArrayListAddressBook class? (The driver puts this in his/her report since it is code)

  5. Open at the AddressBook interface by double clicking on the file in the Package Explorer. Which method(s) does the ArrayListAddressBook class not implement? (driver)

  6. We need to implement that method.

    Scroll down to the end of the file (ArrayListAddressBook) and add a blank line before the last }. Make a blank line and hit Ctrl+Space. (Mac users: Really use Control key, not Command). Pick remove from the drop-down menu.

    What happens? (The scribe puts this in his/her report since it is not code)

    Mac Users: The Eclipse Ctrl+Space hot key combination may conflict with a Spotlight hot key combination. If you are in this situation, use your favorite search engine to look for “mac eclipse ctrl space” or follow this link.

  7. Save your file. What happened to the “abstract class” error message? (scribe)

    Note: We will supply a better implementation of the remove method in the next lab.

D. Implementing Getters and Setters

  1. What is the first of the remaining errors in the ArrayListAddressBook class?

  2. In which class does it need to be fixed?

  3. Add private fields namekey, and value in that(?) class, all of type String.

    Then move the cursor in a blank line below those fields and hit Ctrl+Space.

    Select getName. Repeat twice, selecting getKey and then getValue. Repeat once more to add setValue.

    question markWhat happens?

    If you still do not get the (?) in C.3, answer the following questions:
    1. What does new keyword do?
    2. What is Item(in.nextLine(), in.nextLine(), in.nextLine()) ? To save time, hover the mouse cursor on the (X) sign appeared on the left of that line. Eclipse will provide you the problem detail. If you still not know what the problem is, the answer to (?) is mentioned in D.2.
    3. Check out the input file, are you able to find out what values of name, key, and value (in respected order) are?
  4. Now you know why we make you use Eclipse and not BlueJ. As you work with more sophisticated programs, you want all the support that you can get from a professional development environment.

E. Implementing a Constructor

  1. Save all files (File →Save All from the menu). What error message do you get now?

  2. You need to add an Item constructor. Go to the Item class, put the cursor on a blank line, and hit Ctrl-Space.

    Which option do you choose?

  3. What code is generated when you choose it?

    Add the String parameters to the constructor header in this order: name, key, value.

    Also assign the parameters to the instance variables.

    Your code should now be free from errors.

You may be wondering why you do not see the import for ArrayList and yet the code compiles. Click on the (+) at the top of the file, and you will see all the imports. Eclipse hid them to make the display clearer.

F. Adding a Main Method

  1. Look at the Projects window at the left side of the Eclipse window. Right click on Lab1 project listed on the project workspace , select Run as → Java Application → Lab1 from the menu.

    What happen?

  2. Right-click on (default-package) in the Projects window and click New → Class. Enter AddressBookDemo in the Name field. Add a main method

    public static void main(String[] args) 
    {
       JFileChooser
    }

    then move the cursor next to JFileChooser and hit Ctrl+Space. (To Mac users, check out the tip at the bottom of the lab before proceeding)

    What happens?

  3. Continue editing the main method like this:

    JFileChooser chooser = new JFi

    Hit Ctrl+Space again.

    What happens?

  4. Select the default constructor and then add the following line:
    JFileChooser chooser = new JFileChooser();
    int result = chooser.show

    Hit Ctrl+Space again.

    What happens?

  5. Pick showOpenDialog. Continue editing the main method like this:

    JFileChooser chooser = new JFileChooser();
    int result = chooser.showOpenDialog(null);
    if (result == JFileChooser.)

    Use the auto-complete option and pick APPROVE_OPTION.

    Continue editing the main method like this:

    JFileChooser chooser = new JFileChooser();
    int result = chooser.showOpenDialog(null);
    if (result == JFileChooser.APPROVE_OPTION) 
    {
       String filename = chooser.getSelectedFile().getPath();
    }         

    Where were you able to let Eclipse do the typing for you by strategic use of Ctrl+Space?

  6. After getting the file name, make a variable book of type AddressBook inside the if block. Initialize it with a new ArrayListAddressBook.

    (Note that the type of the variable book is the interface type AddressBook, not the class ArrayListAddressBook. It is a good idea to use the more general interface variables. It will make your code more flexible as we will see later.)

    What is your code?

  7. Still inside the if, call the load method on the book variable to load the file that was returned.

G. Running the Program

  1. Save this file as deptdir.txt somewhere on your hard disk. Run the program (See E.1). In the file chooser, navigate to whereever you saved the deptdir.txt file, and click on Open.

    What happens next?

  2. Add code to the program that looks up the phone number of Dr. Khuri (the CS department chair) and print it to the console window. Notice the keys start with uppercase. (Look in the file for the possible keys.) Use only the last name. What is the code?

  3. Add code to the program that adds your email address to the address book, then save it. What is the code?

  4. What happens when your program runs?

H. Implementing toString and equals

  1. Add the following method to ArrayListAddressBook:
        public Item getFirst()
        {
            return items.get(0);
        }
  2. Next, add a call System.out.println(book.getFirst()) after the call to book.save() in AddressBookDemo.

    What happens? Why?

    (If you do not get an error, you didn't declare book to have type AddressBook. Retrace step E6 and fix it up.)

  3. Add the getFirst method to the interface. Run the program.

    What output do you get?

    We'll fix that strange output in the next steps.

  4. To fix this output, you need to implement a toString method. For which class?
  5. Implement it. What is your code?
  6. What is the output of the program now?
  7. Add the following method to the AddressBook interface:
    boolean contains(Item anItem)

    Add the implementation of that method in ArrayListAddressBook. Remember to use Ctrl-Space. Change the body as follows:

    public boolean contains(Item anItem)
    {
       for (Item it : items)
       {
          if (it.equals(anItem)) return true;
       }
       return false;
    }

    Provide a suitable Javadoc comment for this method. What is your comment?

  8. Now create a new class and run this tester:
    public class ContainsTester
    {
       public static void main(String[] args)
       {
          AddressBook book = new ArrayListAddressBook();
          book.put("Fred", "wife", "Wilma");
          book.put("Dino", "food", "meat");
          System.out.println(book.contains(new Item("Dino", "food", "meat")));
          System.out.println("Expected: true");
          System.out.println(book.contains(new Item("Dino", "wife", "Wilma")));
          System.out.println("Expected: false");
       }
    }

    What does the program print?

  9. Make a walkthrough to the first call of contains. The items array list contains two items. What are they? What is the value of the variable anItem? What happens in the first iteration of the for loop? What happens in the second iteration of the for loop?
  10. Why doesn't the method work correctly?
  11. To fix this, you need to implement an equals method. For which class?
  12. questionImplement it. (Remember that the equals method takes an Object parameter.) What is your code?
  13. What is the output of the ContainsTester program now?

optional I. Adding the Comparable Interface

  1. Change the getFirst method of ArrayListAddressBook to
        public Item getFirst()
        {
            return Collections.min(items);
        }

    What error do you get?

  2. How do you fix it? (Remember that the two major reasons a symbol can not be resolved is: 1. There is a spelling error. 2. Something needs to be imported. )
  3. What error do you get now? Why?

    Hint: The Javadoc for Collections.min is a bit confusing, but think about what this method must do. It is given a collection of arbitrary objects. It doesn't know what objects. Yet it must determine which one is the smallest.

    In other words, Collections.min takes in an ArrayList of Comparable objects as its argument. Now, answer the following questions:

    1. What is the reference name of the ArrayList object that is passed to Collection.min as argument?
    2. What is the data type of all objects the ArrayList contains? Is that type be defined as Comparable ? If not, what would you do to make it become Comparable?
  4. There are two choices—to implement the Comparable interface or to make a Comparator object. Let's do the interface.

    Which class needs to implement it?

  5. Add the implements Comparable clause to that class. Save the file.

    What additional error do you get now?

    Can you ”fix” it with Ctrl-Space?

  6. Ok, it's not really fixed—you still need to provide the code for the compareTomethod. If you do not remember the header for the compareTo method, look it up.

    What is the code of your method?

    At this point, all bugs should have gone away. Ignore warnings about unchecked or unsafe operations—that's because we don't use Comparable<Item>. That is an advanced topic for another time.

    In general, you should not ignore warnings. Don't do so unless you know exactly what is causing the problem. In this case, we have not learned enough to implement Comparable correctly.

  7. Your program should now run without errors.

    What does it print?

optionalJ. Writing a Generic Method

  1. Add the following class to your project:
    import java.util.ArrayList;
    
    public class Util
    {
       /**
          Returns the smallest element in an array
          @param values an array of non-null Comparable values of length >= 1
          @return the smallest value in values
       */
       public static Comparable smallest(Comparable[] values)
       {
          Comparable smallestSoFar = values[0];
          for (int i = 1; i < values.length; i++)
             if (values[i].compareTo(smallestSoFar) < 0)
                smallestSoFar = values[i];
          return smallestSoFar;
       }   
    
       /**
          Returns the smallest element in the array larger than a given value.
          @param values an array of non-null Comparable values
          @param after a value that may or may not be present in the array
          @return the smallest value in the array larger than value, or null if there isn't one
       */
       public static Comparable smallestAfter(Comparable[] values, Comparable after)
       {
          return null;
       }
    }

    Add the following method to AddressBook:

    Item getNext(Item previous);

    Add the implementation of that method in ArrayListAddressBook as a stub.

    Insert this in the body:

          Item[] itemArray = new Item[items.size()];
          items.toArray(itemArray);
          Comparable result = Util.smallestAfter(itemArray, previous);
          return result;

    There is an error in the body.

    Why? (Look at the return type of the method and then look at the data type of result.) How do you fix it?

  2. Now we want to implement the Util.smallestAfter method. Discuss with your buddy how you can do this. Write pseudocode on a piece of paper. Write your and your buddy's name on the paper and turn it in after the lab.

    Pseudocode is just like Java code, except you can use words and phrases such as

    if values[i] is less than values[j]

    or

    while i goes from 0 to the end

    Note: Be sure that you are designing the method to do the right thing. For example, if values contains the Integer objects 2, 6, 5, 4, 1, 7, the call Util.smallestAfter(values, 5) should return 6, the smallest value after 5.

  3. Walk through the pseudocode with the call
    smallestAfter(values, 5)

    where values contains the Integer objects 2, 6, 5, 4, 1, 7

    Make a sheet for all the variables in your pseudocode, write their initial values, execute the steps in your mind, cross out values as they change and replace them with their new values.

    Turn in your sheet after the lab.

  4. Now turn your pseudocode into Java.

    What is it?

  5. Provide a class UtilTester whose main method makes an array values containing the Integer objects 2, 6, 5, 4, 1, 7:
    Integer[] values = { 2, 6, 5, 4, 1, 7 };

    Call Util.smallestAfter(values, 5) and print the result, then print the expected result.

    System.out.println(Util.smallestAfter(values, 5));
    System.out.println("Expected: 6");

    What is the output of that program?

  6. Will your code work if there is no number bigger than the given number? Change the 5 to 7 in UtilTester and run again.

    What do you get? Is it what you expected?

optionalK. Sorting

  1. In the AddressBookDemo program, add code to print the second item (in sorted order). How do you do that?

    Hint: getFirst, getNext

  2. Using the getFirst and getNext methods, print the third item (in sorted order) in the address book.

    What is it?

  3. What is your code to get the third item?
  4. Using getFirst and getNext repeatedly, how can you print the address book items in sorted order? Give pseudocode. What is it?
  5. Now turn your pseudocode into Java.

    What is it?

  6. Put that code into your program.

    What is the output?

  7. Ok, that's nice. We can now print the address book in sorted order. But wouldn't it be nice if we could do this for any Comparable objects, not just for Item objects?
  8. Using Util.smallest and Util.smallestAfter repeatedly, how can you print the contents of an array in sorted order? Give pseudocode.

    What is it?

  9. Use that pseudocode to implement a static method in the Util class
    public void printSorted(Comparable[] values)

    What is your code?

  10. Write a new program that calls Util.printSorted on
    Integer[] values = { 2, 6, 5, 4, 1, 7 };

    What is your program?

  11. What is the output?

  12. Modify your program so that it sorts
    String[] words = { "Mary", "had", "a", "little", "lamb" };

    What is the output? (Remember: "Z" comes before "a")

  13. What is the benefit that you got from using the Comparable interface in the Util class?