CPS 1 Java Review

A great way to get a handle on all the Java tools you've learned this semester is use them to build a program. The example covered in this review is very similar to something you've seen in lecture: the Lib1 and Lib2 classes that used Book objects to create a database of books.

Here's the problem: you've been hired by a small publishing company to computerize their filing system. Your first job is to write a program to record all the titles the firm carries. The system must be able to record a book's author, title, and price; it must allow the company to add new titles to the list easily; and it has to support search for books either by title or author. To see what your finished product should look like, click here

How to use this document:   This example program incorporates nearly everything you've learned about Java to date. You should read through it, think about it, and when you're sure you understand it, put it away and try writing these two classes with nothing to help you but the problem specification given in the paragraph above. If you can't, then you don't understand it yet.

At various points throughout this text, you'll find certain keywords in blue. They're links to further explanation and examples of the meaning of that word, so you can think about that meaning before you continue to read. The links are just to text at the end of this document, though, so if you want to print out everything, you only need to hit print once. Hopefully, more of these links will be added between now and the time you take your exam.

One way to get explanations for stuff you don't understand is to send email to Steve or Greg. If your question is about something in this review, we'll try to add something to address it. And, as always, when you find the inevitable bugs and goof-ups herein, send us email ASAP, so we can take care of it. There might even be a bonus point or two in it.

Classes you will need

There are two. The first will be the applet, the part that runs in a web browser and does most of the active work of the program. In case you didn't know, all the applets you've written in lab are classes. You might have picked that up from one of the lines at the beginning of each lab: public class DecisionTree or public class Calculator, for instance. When the applet is run, an object is created: a DecisionTree or a Calculator or a Widget: they're all objects. So you've been writing classes that come to life as objects all along, maybe without realizing it. This particular class will be called BookList.

The second class you'll write exists only to be used by the first. Its sole function is to store all the information about an individual book (author, title, price). It does no other work. We'll call it BookRecord, and start writing it first.


Writing BookRecord

Getting Started

You should already know from memory the first thing needed when you're writing a new class: the import lines at the top. Go ahead and do the usual ones:

import java.awt.*;
import awb.*;

Now we open our class with this line:

public class BookRecord
{

Why doesn't it have the normal extends java.applet.Applet? Because this class isn't an applet. It doesn't run in a web browser, doesn't have an init() method, doesn't do anything except store information about a book that will be useful to a larger program.

Declarations

A BookRecord has to store three things: a book's author, its title, and its price. That means we'll need two Strings and a double. Note that we DO NOT need any StringFields or DoubleFields. Our BookRecord class never shows up on the screen; it is only information storage and thus stays in the background.

String author, title;
double price;
The Constructor Method
public BookRecord(String a, String t, double p)
{
   author = a;
   title = t;
   price = p;
}
Other methods

In a class that's used mainly for data storage, the most important methods (and often the only ones) are those that allow objects of another class to get and set the data members. In a BookRecord the data members are author, title, and price; we'll need methods to set and get each of those. This method sets author to something new:

public void setAuthor(String a)
{
   author = a;
}

The first line of every method is called the method signature and is made up of four parts:

After this method is called, author is set to whatever the parameter a held. Here's the method to get the value of author.

public String getAuthor() 
{
   return author;
}

Almost all methods whose names begin with get have some return value. This method returns author, which is a String, so the second word in its signature is String. Also, most methods of this kind don't take arguments.

The rest of the methods in BookRecord do the same things for title and price. To see the whole BookRecord class, click here.

Summary

The BookRecord class is a template for objects whose purpose is to store information about books. These BookRecords are not especially useful by themselves, but a collection of them used by another class with the ability to manage them is exactly what we want.


Writing the BookList class

The beginning lines

This class is the part of the program that interacts with the user. It's an applet, so the beginning lines of the code should be familiar to you.

import java.awt.*;
import java.awb;

public class BookList extends java.applet.Applet
{
Declarations

What do you need to declare? The program needs to accept user input of a String for author, a String for title, and a double for price. As usual, it's useful to have a variable corresponding to each field as a place to store information you get from the screen, so you'll need two Strings and a double. There has to be a Button to add a new book's information to the database, a Button to search for a book based on the author's name, and one to search based on title.

One very important piece of the class that won't show up on the screen is the actual list of BookRecords. Any time we need to keep a list of items, we use an array. The syntax for declaring and creating arrays is a little tricky, so pay close attention to the example.

We may discover more things to declare as we write the program, but for now we'll declare these.

BookRecord list[];
StringField authorField, titleField;
String author, title;
DoubleField priceField;
double price;
Button addButton, aSearchButton, tSearchButton;

The init() method

init() must set up everything that we want to be true when the applet starts running. That includes constructing anything that needs to be constructed and adding to the screen the things that should appear on start-up. A common mistake in writing init() is trying to construct ints, Strings, and doubles, none of which needs to be constructed.

The first line of the init() body creates an array of BookRecords with space for 100 elements. To begin with, though, it's empty. Make sure you understand this line.

public void init()
{
   list = new BookRecord[100];		

   authorField = new StringField(18);
   titleField = new StringField(25);
   priceField = new DoubleField(6);
   
   authorField.setLabel("Author:");
   titleField.setLabel("Title:");
   priceField.setLabel("Price:");

   addButton = new Button("Add:");
   aSearchButton = new Button("Author Search:");
   tSearchButton = new Button("Title Search:");

   add(authorField);
   add(titleField);
   add(priceField);
   add(addButton);
   add(aSearchButton);
   add(tSearchButton); 
}

Notice the method signature of init(): the return type is void, because init() returns nothing.

Writing the action method
public boolean action(Event e, Object obj)
{

The method signature of the action() method tells you this: its protection status is public, its return type is boolean, its name is action, and it has two parameters, an Event and an Object.

The action() method handles events. The only events you'll see in CPS 1 are Button clicks, so that's all your action() methods need to deal with. That means you need to write one conditional for each Button; this action() will have three. First, addButton.

The conditional for addButton
if (e.target == addButton)
{

e is an object of type Event; an Event is created every time a Button is clicked. e.target is, naturally enough, the target of the event, the Button that was clicked. If the target was addButton, then your program assumes the user has already typed the author, title, and price of the book to be added to the list, and gets that information from the fields on the screen. Each piece of information is stored in a variable we declared at the top of the class.

author = authorField.getString();
title = titleField.getString();
price = priceField.getDouble();

Now the less familiar part. Once you know a book's author, title, and price, you have all the information you need to create a new BookRecord. Here's the line of code that actually does the work of creating:

BookRecord thisBook = new BookRecord(author, title, price);

Now we need to add the new BookRecord to the array. In order to do that, we have to know the array location where it belongs, and that means keeping track of how many elements have been added to the array altogether. If you were writing the code for this program, you'd go back to the top and declare an int numElements, and initialize it to 0 in init(). Now we can store the BookRecord in the array.

list[numElements] = thisBook;

Recall that list is the name of the array of BookRecords. list[numElements] is read "list-sub-numElements", and is the syntax for referring to a particular location in the array list. For instance, if you're adding the first BookRecord to the array, and numElements is consequently 0, then after this line list[0], the first spot in the array, contains thisBook.

The two lines above could have been legally combined into a single line:

list[numElements] = new BookRecord(author, title, price);

in case you were wondering.

Wrapping up the body of the conditional

Now that we've added an element to the array, we need to do the bookkeeping step of adding one to our count. Then we return true and close out the conditional body.

   numElements = numElements + 1;
   return true;
}
The conditional for aSearchButton

A user must be able to search for a book by its author; your program has to loop through the list of BookRecords and find the book whose author matches the name entered by the user, and then provide the other information (title, price) about that book. First, look over the code for the whole conditional: an explanation follows.

if (e.target == aSearchButton)
{
   author = authorField.getString();
   
   int i = 0;
   while (i < numElements)
   {
      String thisAuthor = list[i].getAuthor();
      if (thisAuthor.equals(author))
      {
         String thisTitle = list[i].getTitle();
         double thisPrice = list[i].getPrice();
         titleField.setString(thisTitle);
         priceField.setDouble(thisPrice);
      }
      i = i+1;
    }
   return true;
}
The finished product

There's another if statement in the action() method, this one for tSearchButton. It's quite similar to the one we just did, but if you want to see it, you can look at the complete BookList code. If you want to try out a version of the program that includes a clear button to make things easier, click here.

That's it. This program covers just about all the Java you've learned so far. If you have any questions, come to a review session or send email to Steve or Greg. If you spot a mistake in this text, send us mail.







Declarations

All variables in Java have to be declared before they can be constructed or have values assigned to them. Declaration consists of putting the type and name of a variable on a line, either by itself or with an assignment to the new variable. Examples:

Variables can only be used between the innermost pair of curly braces within which they are declared. This space is called the scope of a variable

Go back to the top


Variables

Variables store objects or values under a name by which they can be called. Every variable has a type, and can only store things of that type. From another perspective, a variable can store anything in its type; its contents can vary. For instance, if we make the following declaration:

double myDouble;

We have access to a variable of type double known as myDouble, which can store any double assigned to it. We can store the number 7.3 in myDouble like this:

myDouble = 7.3;
This is also legal:
double myDouble;
double yourDouble;
yourDouble = 7.3;
myDouble = yourDouble;
That sequence leaves 7.3 in myDouble. More examples:

A variable can only store one thing at a time

Go back to the top


Methods

In computer programming, as in most kinds of problem-solving, a necessary part of most solutions is division into subproblems. That's the idea behind methods, programming devices that perform a specific, usually limited task. The advantage of wrapping a particular function in a method is the ability to call the method repeatedly to perform the same task over and over, rather than copying and pasting code to acheive the same effect.

A method consists of two parts, the method signature and the method body. Let's look at an example of a method and then look at its pieces.

public int doMathStuff(int i1, int i1)
{
   i1 = i1/i2;
   i1 = i1+i2;
   i2 = i2-i1;
   return i2;
}

There are four parts of a method signature:

The method body is all the stuff inside the curly braces, where the work of the method gets done. This particular method body just does some arithemtic on its parameters and returns the changed form of one of them. It's important to note that somewhere in its body, this method had to return an int, because that's its return type

Fun Facts About Methods