221 In-Lab Page
Fall 2005
Lecture Schedule
In-Lab 1--September 12, 2005
Design a class to work with time
Your class should allow you to:
- set the value of a Time object
- add time to the value of the Time object (in hours and minutes, or in minutes only)
- output the value of the Time object
- compare two time objects, to see which is earlier
- distinguish between am and pm
Output might look something like this
8:40am + 30 minutes is 9:10am
11:15am +3 hours and 30 minutes is 2:45pm
8:40am is earlier than 2:45pm
Your Design should include:
- An interface that the class itself will implement.
Remember that an interface in Java is a way to specify the names,
parameters, and return values of the methods that the class will use
without specifying how the methods perform their operations and
without specifying how the data is internally represented.
- Constructors are not included in an interface, but I would like to
see the signature of the constructors you intend to use. You will
need to comment them out when you try to compile your interface.
- Since this is a review exercise as well as a design exercise, I am
going to specify that two of the methods to be included are:
- the toString( ) method which returns a String and has no argument, and
- the compareTo( ) method which returns an int and takes an argument of type Object.
Both of these methods are routinely included in user-defined classes,
and are inherited from the class Object, then overridden in the user-defined
class.
To Hand in:
Everyone should work individually on this assignment, but I certainly
encourage you to discuss different design options and possibilities with
others in the class.
Turn in the Java interface for this problem, written with Java syntax, with comments as described in the text.
In-Lab 2--September 19, 2005
Arrays, Exceptions and File I/O
Start with this Fraction class.
Get #1 below working before modifying your program for #2.
Then when #2 is working, modify it for #3.
- Write a main( ) program that obtains an arbitary number of
fractions from the user (max 20), stores them in an
array of Fractions, averages them, and displays the the fractions and their average.
- Catching Exceptions: Add try and catch blocks to your program in case
of exceptions thrown by erronous user input. Input errors from the user
should not cause your program to crash. Test this by entering incorrect
data.
- Modify your program so that it takes the input from this
data file instead of the user, then outputs
the results to a file called results.txt.
Hand in: Hand in your source code. William will tell you what he wants you to demo.
In-Lab 3--September 26, 2005
Test a Class
Due to the problems with esus, this lab will be due October 3, 2005
The class DVD_Collection is a class designed to keep track of a DVD collection.
Your job is to write a driver that tests each and every method in the
DVD_Collection class.
What to do
- Download and compile the files you need. These include
DVD_Entry.java and
DVD_Collection.java.
- Note that this class is much like the PhoneDirectory class that we looked
at during our classtime.
- Because time is limited in an in-lab, I have written part of the
driver for you. You are welcome to use as much or little of it as you want.
- The driver as written so far has three methods:
- The main( ) method which calls a menu method to find out
what the user wants to do.
- The menu( ) method which outputs to the screen the user's options,
then returns their choice as an int.
Since this method is not
called with an object, it is a static method, as are all the
methods written in main.
- The loadFile( ) method, was written mostly to help you with the Java
syntax of writing static methods in main.
- The menu offers the user eight choices. Implementing these choices will
test the methods in the DVD_Collection class. Be sure you take a look at
the output to be sure everything is working correctly every time you test
one method.
- Note that the comments are very terse. This is because I want you to
be able to tell what the code is doing, and how it is doing it
by reading the code. In a real
enviroment, the comments should give the reader more help with what
the code is doing.
Hand in: Hand in the source code
from your driver. William will tell you what he wants you to demo.
In-Lab 4--October 3, 2005
Inheritance and Abstract Classes
The basic assignment is to do the programming exercises on #2 on page 143
and #2 on page 154 but I will add a few comments/instructions here.
- Use the class Computer and
Laptop we talked about in class.
- As the exercise mentions, there are many differetnt kinds of
computers. An organization may have servers, mainframes, destopPCs,
and laptops. There are also personal data assistants and game computers.
So it may be more appropriate to declare class Computer as an
abstract class that has an actual subclass for each category of computer.
- Write an abstract class Computer that defines all the methods shown
above and declares an abstract method with the signature costBenefit(double)
that returns the cost-benefit(type double) for each category of computer.
- Besides the Laptop subclass, design at least three or four other
subclasses, but you may leave all but one of the abstract.
(This means the methods in the class will not have to be implemented.)
- You must make one other subclass besides the Laptop class
concrete. (So you must end up with two concrete classes.)
- You can devise any parameters you want to get values for CostBenefit( ).
- You will need to test your classes. Do this in a driver that declares an
array of type Computer, then puts several instances of of your
subclasses into the array (put them in any way you want, hard-code,
interactive input, or file input).
- Your driver should call the overridden methods of both the subclasses to
test them, and see that they actually do different things, even if it is
just figure cost-benefit and output.
Extra Credit: Write a clone method for class Laptop.
In-Lab 5--October 10, 2005
Building a Hierarchy
The basic assignment is to do the programming exercises on #4 on page 189.
I am reproducing the assignment here in case you do not have your books.
I will also add a few notes at the end.
You will do the design work and start on the implementation in class today.
The entire program will be due in two weeks. It is your next outlab.
Write a banking program that simulates the
operation of your local bank.
You should declare the following collection of classes.
- Class Account
- Data fields: customer (type Customer), balance, accountNumber, transactions array (type Transaction[ ])
- Methods: getBalance( ), getCustomer( ), toString( ), setCustomer( ), setBalance( ), clone( )
- Class SavingsAccount extends Account
- Methods: deposit( ), withdraw( ), addInterest( )
- Class CheckingAccount extents Account
- Methods: deposit( ), withdraw( ), addInterest( )
- Class Customer
- Data fields: name, address, age, phone custNumber
- Methods: Accessors and modifiers for data fields
- Classes Senior, Adult, Student all these classes extend Customer
- Each has constant data fields SAVING_INTEREST, CHECK_INTEREST, CHECK_CHARGE, and OVERDRAFT_PENALTY, that define these values for customers of that type.
- Class Bank
- Data fields: accounts array (type Account[ ])
- Methods: addAccount( ), makeDeposit( ), makeWithdrawal( ), getAccount( )
- Class Traction
- Data fields: customerNumber, tranactionType, amount, fees (a string describing unusual fees)
- Methods: processTrans( )
Notes:
- You should draw a diagram to indicate the hierarchy. The diagram should include a box for each class with the instance variables and method headers. Include arrows from a subclass to a superclass.
- Start implementing the classes highest in your hierarchy first. You can stub in methods that you don't need immediately.
- Decide which, if any of your methods should be abstract.
- You should include toString and clone methods in all classes
where you think they would be useful.
- You will needto write an allplication class that interacts with the user.
In this application you should first open several accounts and then enter several transactions.
Hand in: William will tell you what he wants
handed in today.
In-Lab 6--October 17, 2005
Introduction to Linked Lists
During today's in-lab, you are going to work with some
linked list classes. Before beginning the lab, download the following two
files and put them into a project called Lab6. List.java, and UseList.java, Open them in
the BlueJ compiler. You will need to look at them to do the lab.
Familiarize yourself with the code in these files and then do as many of
the following as you can in the time permitted. (No one is expected to get
them all done) The first is mandatory, you may choose to do the others in
any order you wish. You must turn in your code at the end of two hours.
What to Do
- On a sheet of paper, walk through the code, starting with main, and
drawing the new nodes as they are created. Add three nodes using the addToEnd( ),
method, reassigning the pointers as directed by the code. Any local variables should be shown,
and then crossed out as the method returns.
- Write an addToFront( ) method.
- Write an addUnique( )method so that it does not allow an element
that is already in the linked list to be inserted again. In this case an
appropriate error message should be printed. Add some statements to
UseList to check your changed method. Note that the String class includes
a compareTo method which you should use.
- Write an method called remove ( ) that removes an element (if it
exists) from the linked list. Remove should return a boolean so the client
knows whether
or not the removal was successful. It should be tested in UseList
- Write an addSorted( ) method so that it keeps the elements in
sorted order as they are inserted.
Hand in:
- A printout of your modified code.
- A printout of runs of your changed methods showing that they do work.
In-Lab 7--October 24, 2005
Using the Linked List class
This lab has several parts: the first two parts should take no
more than 30 minutes or so. The majority of your time should be
spent on the last part
What to do
- Study the documentation for a LinkedList class in the Java API.
Pay special attention to the methods that are available to you.
- Write an simple application program that uses a LinkedList. Your application
should:
- Create a LinkedList to hold Strings
- Put the following String items in the list (unordered for now)
Tom Dick Harry Jane Mary Julie (You can hard code this if you wish)
- Output all the items in the list
- Output every other item in the list
- Remove Jane from the list; output the list to test
- The KWListTester code we looked at in class should help you do
this quickly and easily.
- Implement a class that uses the LinkedList class to store lists
that are always in order. This is the class you designed in lecture
on Friday.
- Extra Credit: Create a linked list of DirectoryEntries that are always in order.
- This class will have to implement the comparable interface for it
to work with your OrderedList. So you will have to add a compareTo
method to it.
In-Lab 8--October 31, 2005
Using Stacks (i.e. Stack Applications)
(and textbooks)
This lab has several parts. If you ignore the first part, there is not
much hope that you will complete the lab.
What to do
- In your textbook, read pages 279 - 288. You should
have done at least part of this before coming to lab.
- Download the ArrayStack class given here.
It is almost the same as the Stack class
we looked at in lecture. It implements the Stack
Abstract Data Type using an ArrayList.
- Write a class that evaluates a postfix expression. Be
sure that it compiles and works correctly.
- Make sure that this class uses the ArrayStack and not
the Stack that is implemented in the Java Library (which
extends Vector).
- The input for this class should be a string -- the postfix expression
- To use the class to evaluate a postfix expression, create an
object of type PostfixEvaluator, then that object should call its
public method eval( ) to evaluate the expression.
- Tuesday: Here is the PostfixEvaluator
class I gave you in class Monday.
- Modify this class that converts an infix
expression to a postfix expression without parentheses to
one that can handle parentheses.
- If there is any of this code you do not understand, I encourage
you to ask the TA about it. Part of what I want you to
learn from this is constructs we have not used much.
- Be sure to insert in the above two classes a nested Exception class.
- Write a driver which accepts an infix expression, then,
transparent to the end user, converts it to postfix, then evaluates it.
It should output the result of evaluating the infix expression.
Things you should notice
- Wrapper classes
An ArrayList (and thus an ArrayStack) can only hold objects,
not primitives. So the integers in the infix and postfix expressions
are wrapped in an Integer class. You should notice when an int
is changed to an Integer, and an Integer is changed back to an int.
- StringTokenizer
When an postfix expression is evaluated, the entire expression is read
as one string, then StringTokenizer is used to break the string
down in to its individual tokens.
- indexOf Strings
Your book has a clever way to tell if a character is an operator (as
opposed to an operand, an integer here). Be sure you understand what
is going on.
- You should also notice the use of a nested Exception class. This is good practice.
In-Lab 9--November 7, 2005
Recursion
Suppose you have an array of integers, and you want to find the
largest one using recursion (yes, I know you can do it easily using
iteration, but I want you to learn how to design and implement
a recursive solution!)
The problem
Assume you have an unsorted array of int from which you want to find
the largest item. The pseudo code for the recursive solution you
should implement is:
max(int[] anArray)
if (anArray has only one item)
{the item is the maximum }
else if (anArray has more than one item)
{ the maximum will be the maximum of two recursive calls:
max(left_half_of_anArray) and
max(right_half_of_anArray)
}
Part 1: The Design
To implement this you will have to consider some of the
items we considered when inplementing the recursive binary search
in class and some additional ones as well. Briefly these are:
- How do you pass half an array to each recursive call?
- What should the base case be? If you don't get it right you
will run into infinite recursion, so give it very careful
consideration!
- One difference between this and the binary search is that
you must conquer both of the subprograms, not one as binary search does.
- You must find the maximum of the two maximums returned by the two
recursive calls.
I strongly urge you to figure out the solution to these problems before you
start to code. It will be more difficult to think in Java than it is in
English.
Part 2: The Implementation
This will be a static method. The main method that calls it
has been written for you inside a class called
Max_recursive.java.
Your max( ) method can be in the same class.
You can write this method in less than 20-30 lines of code
Do NOT feel you must
get started writing code right away. Much more thought than typing must go into this
exercise!!
Hand in:
The source code for the class max( ) and a run showing your
solution works.
In-Lab 10--November 14, 2005
Linked List Review
Since we have an exam Wendesday, which will cover linked lists (among other things)
and since it has been a while since you have worked with linked lists, today's lab
is on linked lists.
I am giving you two files:LListReview.java,
and UseListReview.java, Open them in
the BlueJ compiler.
- The first is a linked list class with the implementation of some of the code missing.
- Note this is a double linked list with two nested classes, the NodeR class,
and the IteratorR class.
- The second is a class to test the code you write in the first.
- This class is written so you can test the code you write progressively;
just uncomment a section to test the next methods.
- For instance, you can test the first three cases of the
add method below before you work on the fourth case. To
test the fourth case, just uncomment the code that would test it.
Rememberan iterator class has has these three instance variables:
private NodeR< E > nextItem;
private NodeR< E > lastItemReturned;
private int index = 0;
When we wrote our own code to iterate through a list, the
instance variable above nextItem we called curr
or currItem, and the lastItemReturned we called prev or prevItem. We used prevItem
to trail currItem through the list, so we could use it if needed. lastItemReturned
does exactly the same thing as the reference variable we used to trail curr.
The code missing from the LListReview class is from the nested class
IteratorR.
- The first method for you to implement is the add method in the
IteratorR class. The add method has four
cases, the first three of which should be fairly simple for you. Some
of the code has been left in the method to help you. Be sure to draw doubly linked
list diagrams to show each case before you try to code it.
- Case 1: Add a node to an empty list.
- Case 2: Add a node to the front of the list.
- Case 3: Add a node to the end of the list.
- Case 4: Add a node to the middle of the list.
- This is really the
only difficult case, and it is not really difficult if you understand
how iterators work. To help you, take a look at the following code
that is called before add in the IteratorR class is called.
- Note that the add in LListReview is called with two arguments:
index and object to be added.
- The index is used to call the method listIterator in the
LListReview class. This method call merely calls the constructor
for the IteratorR class.
- It is imperative that you understand what this constructor
is doing to understand how to code the add function.
- The next bit of code for you to implement is the next and hasNext
methods in the IteratorR class
- To implement the hasNext method, just think about how you
tell if you are at the end of a linked list
- To implement the next method, remember it should
return the item the iterator is pointing to, then move the iterator forward.
In-Lab 11--November 21, 2005
Java Sorting Library & Selection Sort
The lab today will be due November 28, the Monday after Thanksgiving. This
assignment will count for today's in-lab, this week's out-lab and a assignment
in lieu of class on Wendesday November 23.
What to do:
- Read Section 10.1 in your text. It has a lot of information about using the
Java library. Among the items that are covered in this section are:
- The Arrays class, and the overloaded sorting methods found in that class.
- The Collections class and the sorting methods for Lists.
- The interface Comparable with its method compareTo that is the default
way of sorting in the above methods.
- The interface Comparator with its method compare that is an alternate
way of sorting in the above methods.
- At the end of the section on page 518, do Self-Check #1 (a-f), and Programming
#1-#3. Note that 1-3 just ask you to write a method call, which would
be one line, not a complete program. You may want to write more and compile it, just to make sure your call
actually works.
- Read Section 10.2. Selection sort is probably the most intutative way to sort, so this
section is fairly easy. Be sure you understand the algorithm, and how the code
implements the algorithm. The code is in the book, and a slightly different version
is on the web under Friday's lecture for 221.
- At the end of section 10.2 on page 521, do Self-Check #1, 2, 3, and Programming #1 and #2.
Hand in: Give the above assignment to Anne in lecture
Monday afternoon at lecture. She will grade it.
In-Lab 12--November 28, 2005
Sorting and the Java Library
Today's lab asks you to sort a variety of lists. You can write your own sorting algorithm,
or you can use the sorting algorithms in the Java library. I advise using the library.
Note: The code below helps you over some of the syntax problems that do not
specifically deal with sorting, but you will be expected to note the syntax
and be able to use it in the future.
-
To get warmed up: Hint: use the sorts in the Arrays class
- Use the class SortingWarmUp
to do the following: (part has been written for you)
- Create an array of integers, and sort it, and output the sorted list.
- Create an array of Strings, and sort it, and output the sorted list.
- The real problem: Hint: use the sort in the Collections class
- Modify the class Person, that
contains a person's first and last name and social security number.
This class should include the methods necessary work with objects of type Person,
including a way to compare two objects by name. Part of the busy work
of writing the class has been done for you.
- Modify the class PersonArray that
contains an ArrayList of type Person. This class should
have as an instance variable the ArrayList of type Person, and the
methods to manipulate the array, including, but not limited to
asking the user for the data and storing it in the array. This class
has also been partially written for you.
- Modify the class UsePersonArray
to accomplish as many of the following tasks as you have time for:
- Output the unsorted list in the order the user entered it, then sort it
by name and output it.
- Create a Comparator class to sort Persons by social security number, then
sort the list by social security number, and output it.
- Save the data to a file, and modify the code so the file can be read in when
the program is run.
Note: For input above I used the BufferedReader class (since I did not have 5.0 on
the machine I was using) instead of the Scanner class. You can change it if you wish.