Copyright © Cay S. Horstmann 2010-2015 
This work is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 United States License.
Modified by:
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.
eclipse/eclipse
Lab1.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
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
cs46b/labs/lab1 directory. (Be careful not to navigate to the src subdirectory.)If you had trouble in this step, be sure to ask the lab instructor to look over what you have been doing.
ArrayListAddressBook.java, and it will open in the edit windowWhat is the first error in the ArrayListAddressBook class? (The driver puts this in his/her report since it is code)
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)
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.
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.
What is the first of the remaining errors in the ArrayListAddressBook class?
In which class does it need to be fixed?
name, key, and value in that(?) class, all of type String.getName. Repeat twice, selecting getKey and then getValue. Repeat once more to add setValue. new keyword do?name, key, and value (in respected order) are?Save all files (File →Save All from the menu). What error message do you get now?
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?
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.
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?
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?
Continue editing the main method like this:
JFileChooser chooser = new JFi
Hit Ctrl+Space again.
What happens?
JFileChooser chooser = new JFileChooser(); int result = chooser.show
Hit Ctrl+Space again.
What happens?
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?
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?
load method on the book variable to load the file that was returned.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?
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?
Add code to the program that adds your email address to the address book, then save it. What is the code?
What happens when your program runs?
toString and equalsArrayListAddressBook:
public Item getFirst()
{
return items.get(0);
}
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.)
getFirst method to the interface. Run the program.
What output do you get?
We'll fix that strange output in the next steps.
toString method. For which class?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?
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?
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? equals method. For which class?ContainsTester program now?getFirst method of ArrayListAddressBook to
public Item getFirst()
{
return Collections.min(items);
}
What error do you get?
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:
ArrayList object that is passed to Collection.min as argument?ArrayList contains? Is that type be defined as Comparable ? If not, what would you do to make it become Comparable?Comparable interface or to make a Comparator object. Let's do the interface.
Which class needs to implement it?
implements Comparable clause to that class. Save the file.
What additional error do you get now?
Can you ”fix” it with Ctrl-Space?
compareTomethod. If you do not remember the header for the compareTo method, look it up.
o to an Item other. String.compareTo. If the names are different, return whatever String.compareTo returned. Check this out for string comparison examples.value.compareTo(other.value).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.
What does it print?
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?
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.
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.
What is it?
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?
What do you get? Is it what you expected?
AddressBookDemo program, add code to print the second item (in sorted order). How do you do that?
Hint: getFirst, getNext
getFirst and getNext methods, print the third item (in sorted order) in the address book.
What is it?
getFirst and getNext repeatedly, how can you print the address book items in sorted order? Give pseudocode. What is it?What is it?
What is the output?
Item objects? Util.smallest and Util.smallestAfter repeatedly, how can you print the contents of an array in sorted order? Give pseudocode.
What is it?
Util class
public void printSorted(Comparable[] values)
What is your code?
Util.printSorted on
Integer[] values = { 2, 6, 5, 4, 1, 7 };
What is your program?
What is the output?
String[] words = { "Mary", "had", "a", "little", "lamb" };
What is the output? (Remember: "Z" comes before "a")
What is the benefit that you got from using the Comparable interface in the Util class?