Document Sample
W2 Powered By Docstoc
					Week 2

Arrays of Objects
Horstmann 2nd ed., chapter 8

Case Study. Write a program which reads employee data from an external text file and enters it
into an array of objects. The API of the Employee class contains:
 Employee (String name, int age, double salary);
 String getName();
 double getSalary();
and the text file has a line of data as in the following example:

This program will then display in alphabetic order the names of the employees with salaries
between $40,000 and $60,000.

 import java.util.*;
import java.io.*;

public class Driver1 {

public static void main(String [] args) throws IOException {
 Employee emp[] = new Employee [100];
 Employee hold;
 Scanner fileIn = new Scanner(new File("dat.txt"));
 int count=0;

     for (;fileIn.hasNextLine();){
       String str=fileIn.nextLine();
       StringTokenizer st = new StringTokenizer(str,",");
       Employee s=new Employee (st.nextToken(),Integer.parseInt(st.nextToken()),Double.parseDouble(st.nextToken()));

     for ( int pass = 1; pass < count; pass++ ) {
         // loop to control number of comparisons
         for ( int e = 0; e < count - 1; e++ ) {
             if ( emp[e].getName().compareTo (emp[e+1].getName())>0 ) {
               hold = emp[e];
               emp[e] = emp[e+1];
               emp[e+1] = hold;

     for (int i=0; i<count ; i++){

      if (emp[i].getSalary()>40000 && emp[i].getSalary()<60000 )
class Employee {
 private String name;
 private int age;
 private double salary;

public Employee(String n, int a, double s){

public String getName(){
  return name;

 public double getSalary(){
   return salary;

Building Multi-Class Applications
Horstmann 2nd ed., chapter 17

Choosing Classes
  - objects correspond to nouns in the description of your application
  - their behaviour corresponds to public methods contained in their corresponding classes
  - choosing classes is not a trivial task
  - create classes which represent a single concept (see Ex.2.1)

Class Purse shown below there are 2 concepts: a purse that holds coins and the value of each coin.

class Purse {
  public Purse();
  public void addNickels(int count);
  public addDimes(int count);
  public addQuarters(int count);
  public double getTotal();

It is therefore better to rewrite the class as:
class Coin{
   public Coin(double value, String aName);
   public double getValue();
class Purse {
  public Purse();
  public void add(Coin aCoin);
  public double getTotal();
In this case class Purse depends on class Coin as it is using objects of Coin type. Of course, class
Coin does not depend on class Purse.

UML class diagrams

The world of classes and objects is conveniently presented in the Unified Modeling Language
(UML) diagrams.

In UML the relationship between Purse and Coin is represented with an arrow pointing to Coin, the
dependent class:

 Purse                     Coin

If class Coin changes that will imply that class Purse has to be rewritten. In general you want to
minimize the number of class dependencies (low coupling).

Case Study: Printing an Invoice

An Invoice object must hold references to the Address and the LineItems. The Product is turned
into a LineItem object. Invoice contains an ArrayList of LineItems.

public class InvoiceTester{
  public static void main(String[] args) {
    Address samsAddress
        = new Address("Sam's Small Appliances",
          "100 Main Street", "Anytown", "CA", "98765");
    Invoice samsInvoice = new Invoice(samsAddress);
    samsInvoice.add(new Product("Toaster", 29.95), 3);
    samsInvoice.add(new Product("Hair dryer", 24.95), 1);
    samsInvoice.add(new Product("Car vacuum", 19.99), 2);

public class Invoice{
  public Invoice(Address anAddress) {
    items = new ArrayList<LineItem>();
    billingAddress = anAddress;

 public void add(Product aProduct, int quantity) {
   LineItem anItem = new LineItem(aProduct, quantity);
 public String format()
        String r = "             I N V O I C E\n\n"
            + billingAddress.format()
            + String.format("\n\n%-30s%8s%5s%8s\n",
              "Description", "Price", "Qty", "Total");

        for (LineItem i : items)     {
          r = r + i.format() + "\n";

        r = r + String.format("\nAMOUNT DUE: $%8.2f", getAmountDue());
        return r;

     public double getAmountDue() {
      double amountDue = 0;
      for (LineItem i : items) {
        amountDue = amountDue + i.getTotalPrice();
      return amountDue;

    private Address billingAddress;
    private ArrayList<LineItem> items;

public class Address{
  public Address(String aName, String aStreet,
      String aCity, String aState, String aZip) {
    name = aName;
    street = aStreet;
    city = aCity;
    state = aState;
    zip = aZip;

    public String format() {
      return name + "\n" + street + "\n"
          + city + ", " + state + " " + zip;

    private String name;
    private String street;
    private String city;
    private String state;
    private String zip;

public class LineItem{
  public LineItem(Product aProduct, int aQuantity) {
    theProduct = aProduct;
    quantity = aQuantity;
  public double getTotalPrice() {
    return theProduct.getPrice() * quantity;
     public String format() {
      return String.format("%-30s%8.2f%5d%8.2f",
          theProduct.getDescription(), theProduct.getPrice(), quantity, getTotalPrice());

    private int quantity;
    private Product theProduct;

public class Product {
  public Product(String aDescription, double aPrice) {
    description = aDescription;
    price = aPrice;
  public String getDescription() {
    return description;
  public double getPrice() {
    return price;
  private String description;
  private double price;

Case Study: Application Centre for universities admissions.

A student can choose 3 different universities and let us assume that this center will accept up to 100
different applications. This program has to allow the user to:
i) enter the student application,
ii) accept students in some of the universities that they chose
iii) display the status of the applications.

The two obvious classes are the ApplicationCentre and the Student. The Student class is the
dependent class but unlike in the previous example the relationship between the two classes is of
the type one-to-many. The following UML class diagram will specify the relation between Student
and ApplicationCentre.

    ApplicationCentre                               StudentApplication
                                                    - univ1, univ2, univ3: String
    - st[100] : StudentApplication                  - acc1, acc2, acc3: boolean
                                                    - name : String
    + addStudent(): boolean
    + getStudent(int):                              + setAcceptance(): void
    StudentApplication                              + toString(): String

Note: A UML object diagram contains a snapshot of the objects at a certain point in the execution
of the program. The notation will include the names of the objects and the values of the attributes.
We shall note use UML object diagrams in this course.
Java Implementation of the Applications Centre

The Applications class presented below is the driver which allows for the association of
ApplicationCentre and StudentApplication classes. For input/output we shall use JOptionPane, a
class part of the Swing package which produces simple pop-up dialog boxes. (in most of this course
we shall avoid the line input/output used in ITEC1620)


// A class which handles applications for university admission
import javax.swing.JOptionPane;

public class Applications {
   public static void main( String args[] ) {
           ApplicationCentre appCentre= new ApplicationCentre ("Guelph");
           String stopper="quit";
           int nrStud=0;
           StudentApplication s;
// Input data

        JOptionPane.showMessageDialog(null,"Enter student names, each followed by 3 choices of universities. To
stop enter for name the word quit","Input", JOptionPane.PLAIN_MESSAGE);
          String n = JOptionPane.showInputDialog("Student's name ?");
          boolean flag=true;
          while (!n.equals(stopper) && flag){
                   String u1= JOptionPane.showInputDialog("1st university ?");
                   String u2= JOptionPane.showInputDialog("2nd university ?");
                   String u3= JOptionPane.showInputDialog("3rd university ? ");
                   s=new StudentApplication (n, u1, u2, u3);
                   n=JOptionPane.showInputDialog("Student's name ?");

 // Accept some applications

          String line = JOptionPane.showInputDialog(" Indicate which applications are to be accepted by entering the
student index number. To stop enter for name the word quit");
          while (!line.equals(stopper)) {
           int stnr=Integer.parseInt(line);
           line= JOptionPane.showInputDialog("Enter university index 0..2");
           int anr=Integer.parseInt(line);
           s = appCentre.getStudent(stnr);
           line= JOptionPane.showInputDialog(" Indicate which applications are to be accepted by entering the student
index number. To stop enter for name the word quit");

 // Print the final results
              JOptionPane.showMessageDialog(null, " Records for all applicants to "+ appCentre.getName() +
"\n","Records", JOptionPane.PLAIN_MESSAGE);
         for (int i=0;i<nrStud; i++)
           s = appCentre.getStudent(stnr);
            JOptionPane.showMessageDialog(null, s.toString() ,"Records", JOptionPane.PLAIN_MESSAGE);

class ApplicationCentre {
 private String name;
 private StudentApplication [] st;
 private int studentCount;
 private int size;

    public ApplicationCentre(String s){
       st = new StudentApplication[size];

    public String getName() {
       return name;

    public boolean addStudent(StudentApplication s){
     if (studentCount==size) return false;
     studentCount ++;
     return true;

    public StudentApplication getStudent(int which){
            if (which<0 || which > studentCount-1){
               return null;
       return st[which];

    class StudentApplication{
            private String name;
            private String university0;
            private String university1;
            private String university2;
            private boolean accept0;
            private boolean accept1;
            private boolean accept2;

           public StudentApplication (String n, String u0, String u1, String u2){
                    name = n;

           public void setAcceptance(int which){
                 case 0: accept0=true; break;
                 case 1: accept1=true; break;
                 case 2: accept2=true; break;

        public String toString(){
                 String result = name + ":\n";
                 result += university0;
                 if (accept0) result += " - accepted\n";
                           else result += " - rejected\n";
                  result += university1;
                 if (accept1) result += " - accepted\n";
                           else result += " - rejected\n";
                result += university2;
                 if (accept2) result += " - accepted\n";
                           else result += " - rejected\n";
                return result;

The most important concept in this program is the creation and use of the array of
StudentApplication objects st[].

The lines
     st = new StudentApplication[size];
in the ApplicationCentre constructor creates an array of null references:

The lines
       StudentApplication s=new StudentApplication (n, u1, u2, u3);
in the main() of class Applications create the object s of StudentApplication type and then through
the method addStudent() of class ApplicationCentre the address of s is passed to an element of the
st[ ] array.


This operation is repeated in the while loop until either the array is full or the user enters the word
“quit” as the name of the student.

Shared By: