Select a Chapter: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 Back to the Main Page
Chapter Seven listings: 11 classes
import javax.swing.JOptionPane;

public class Ordering
{
/** Ask the user for three Workers. Print the one that is
* last in alphabetical order of names. */

public static void main (String[ ] args)
{
javax.swing.JOptionPane.showMessageDialog (null,
"reading 3 workers, printing the last.");
Buffin infile = new Buffin ("workers.txt");
Worker first = new Worker (infile.readLine());
Worker second = new Worker (infile.readLine());
Worker third = new Worker (infile.readLine());
if (third.getName() != null) // in case of insufficient input
{ javax.swing.JOptionPane.showMessageDialog (null,
"The alphabetically last is "
+ CompOp.lastOne (first, second, third));
}
System.exit (0);
} //======================
}

public class CompOp
{
/** Return the String representation of the last/largest of
* three IComparable values. */

public static String lastOne (Comparable first,
Comparable second, Comparable third)
{ Comparable last = first.compareTo (second) >= 0
? first : second;
if (last.compareTo (third) < 0)
last = third;
return last.toString();
} //======================
}

import javax.swing.JOptionPane;

public class PersonnelData
{
private Buffin itsFile = new Buffin ("workers.txt");

/** Read a file and return the name of the Worker that is
* alphabetically first. */

public String findEarliestWorker()
{ Worker answerSoFar = new Worker (itsFile.readLine()); //1
if (answerSoFar.getName() == null) //2
return "no workers!"; //3
else //4
{ Worker data = new Worker (itsFile.readLine()); //5
while (data.getName() != null) //6
{ if (data.compareTo (answerSoFar) < 0) //7
answerSoFar = data; //8
data = new Worker (itsFile.readLine()); //9
} //10
return answerSoFar.getName() + " is first of all."; //11
} //12
} //======================


private static final int TIME_SPAN = 10;
private static final int YEAR = 1960;


/** Read a file and return the string representation of the
* number of Workers born in each of 1960 to 1969. */

public String countBirthYears()
{ int[ ] count = new int [TIME_SPAN]; // all zeros //1

//== READ THE WORKER DATA AND UPDATE THE COUNTS
Worker data = new Worker (itsFile.readLine()); //2
while (data.getName() != null) //3
{ int lastDigit = data.getBirthYear() - YEAR; //4
count[lastDigit]++; // error check left as exercise//5
data = new Worker (itsFile.readLine()); //6
} //7

//== CONSTRUCT THE STRING OF ANSWERS
String s = ""; //8
for (int k = 0; k < TIME_SPAN; k++) //9
s += (YEAR + k) + " : " + count[k] + " workers\n"; //10
return s; //11
} //======================


public static final int MAX_WORKERS = 5000;

/** Read a file of up to 5000 Workers and display those who
* make more than fifty percent above the average pay. */


public void printHighlyPaid()
{
//== INITIALIZE VARIABLES
Worker[ ] item = new Worker[MAX_WORKERS]; //1
int size = 0; // number of workers in the array //2

//== READ THE WORKER DATA AND ADD EACH TO THE ARRAY
Worker data = new Worker (itsFile.readLine()); //3
while (data.getName() != null && size < item.length) //4
{ item[size] = data; //5
size++; //6
data = new Worker (itsFile.readLine()); //7
} //8

//== CALCULATE THE AVERAGE WEEK'S PAY
double totalPay = 0; //9
for (int k = 0; k < size; k++) //10
totalPay += item[k].seeWeeksPay(); //11
double average = size == 0 ? 0.0 : totalPay / size; //12


//== PRINT THOSE MAKING MORE THAN 50% OVER THE AVERAGE
double highlyPaid = 1.5 * average; //13
String s = ""; //14
for (int k = 0; k < size; k++) //15
{ if (item[k].seeWeeksPay() > highlyPaid) //16
s += item[k].toString() + "\n"; //17
} //18
JOptionPane.showMessageDialog (null, s); //19
} //======================


/** Read a file of up to 5000 Workers and display them
* in ascending (increasing) order of birth years. */

public void printOrderedByYear()
{ WorkerList job = new WorkerList (MAX_WORKERS);
Worker data = new Worker (itsFile.readLine());
while (data.getName() != null && job.size() < MAX_WORKERS)
{ job.insertByYear (data);
data = new Worker (itsFile.readLine());
}
System.out.println (job.toString());
} //======================
} //########################################################


class PersonnelDataTester
{
public static void main (String[ ] args)
{ JOptionPane.showMessageDialog (null, "finding the first");
String out = new PersonnelData().findEarliestWorker();
JOptionPane.showMessageDialog (null, out);
out = new PersonnelData().countBirthYears();//test Listing 7.4
JOptionPane.showMessageDialog (null, out);
new PersonnelData().printHighlyPaid(); // testing Listing 7.7
System.exit (0);
} //======================
}

class OrderedPersonnelDataTester
{
public static void main (String[ ] args)
{ System.out.println ("Workers in order of birth year.");
new PersonnelData().printOrderedByYear();
System.exit (0);
} //======================
}

public class Worker  implements Comparable
{
public static final double WEEK = 40.0; // regular work week
public static final int NUM_DAYS = 5; // days in 1 work week
////////////////////////////////////
private String itsFirstName = null;
private String itsLastName = null;
private int itsBirthYear = 0;
private double itsHourlyRate = 0;
private double [] itsHoursPaid = {8, 8, 8, 8, 8}; // 1 per day


/** Return the first name plus last name of the Worker.
* But return null if it does not represent a real Worker. */

public String getName()
{ return (itsLastName == null) ? null
: itsFirstName + " " + itsLastName;
} //======================


/** Return a String value containing most or all of the
* Worker's data, suitable for printing in a report. */

public String toString()
{ return itsLastName + ", " + itsFirstName + "; born "
+ itsBirthYear + ". rate = " + itsHourlyRate;
} //======================


/** Record the hours worked in the most recent day. */

public void addHoursWorked (double hoursWorked)
{ for (int k = NUM_DAYS - 1; k > 0; k--)
itsHoursPaid[k] = itsHoursPaid[k - 1];
itsHoursPaid[0] = hoursWorked;
} //======================


/** Return the Worker's gross pay for the week. */

public double seeWeeksPay()
{ double sum = 0.0;
for (int k = 0; k < NUM_DAYS; k++)
sum += itsHoursPaid[k];
return sum <= WEEK ? itsHourlyRate * sum
: itsHourlyRate * (sum * 1.5 - WEEK / 2);
} //======================


public boolean equals (Worker par)
{ return par != null && this.itsLastName != null
&& this.itsLastName.equals (par.itsLastName)
&& this.itsFirstName.equals (par.itsFirstName);
} //======================


/** Return 0 if equal, negative if the executor is before
* ob (executor has an earlier last name or else the same
* last name and an earlier first name), positive otherwise.
* Precondition: ((Worker) ob).getName() is non-null. */

public int compareTo (Object ob)
{ Worker that = (Worker) ob;
int comp = this.itsLastName.compareTo (that.itsLastName);
return comp != 0 ? comp
: this.itsFirstName.compareTo (that.itsFirstName);
} //======================


/** Return the Worker's birth year. */

public int getBirthYear()
{ return itsBirthYear;
} //======================


/** Create a Worker from an input String, a single line with
* first name, last name, year, and rate in that order.
* If the String value is bad, the name is made null. */

public Worker (String par)
{ StringInfo si = new StringInfo (par);
si.trimFront (0);
if (si.toString().length() > 0)
{ itsFirstName = si.firstWord();

si.trimFront (itsFirstName.length());
itsLastName = si.firstWord();

si.trimFront (itsLastName.length());
itsBirthYear = (int) si.parseDouble (-1);

si.trimFront (si.firstWord().length());
itsHourlyRate = si.parseDouble (-1);
}
if (itsBirthRate < 0 || itsHourlyRate < 0)
itsLastName = null;
} //======================
}

public class WorkerList 
{
private Worker[ ] itsItem;
private int itsSize = 0;


/** Create an empty list capable of holding max Workers. */

public WorkerList (int max)
{ itsItem = max > 5 ? new Worker[max] : new Worker[5];
} //======================


/** Add all Worker values in the non-null file to this list,
* except no more than there is room for in the list. */

public void addFromFile (Buffin file)
{ Worker data = new Worker (file.readLine());
while (data.getName() != null && itsSize < itsItem.length)
{ itsItem[itsSize] = data;
itsSize++;
data = new Worker (file.readLine());
}
} //======================


/** Return the average pay for all workers in the list.
* Return zero if the list is empty. */

public double getAveragePay()
{ double totalPay = 0;
for (int k = 0; k < itsSize; k++)
totalPay += itsItem[k].seeWeeksPay();
return itsSize == 0 ? 0.0 : totalPay / itsSize;
} //======================


/** Return names of workers making more than the cutoff. */

public String thosePaidOver (double cutoff)
{ String s = "";
for (int k = 0; k < itsSize; k++)
{ if (itsItem[k].seeWeeksPay() > cutoff)
s += itsItem[k].toString() + "\n";
}
return s;
} //======================


/** Tell whether par is a value in this WorkerList. */

public boolean contains (Worker par) // in WorkerList
{ for (int k = 0; k < itsSize; k++)
{ if (itsItem[k].equals (par))
return true;
}
return false;
} //======================


/** Return a new object, a duplicate of this WorkerList. */

public WorkerList copy() // in WorkerList
{ WorkerList valueToReturn;
valueToReturn = new WorkerList (this.itsItem.length);
valueToReturn.itsSize = this.itsSize;
for (int k = 0; k < this.itsSize; k++)
valueToReturn.itsItem[k] = this.itsItem[k];
return valueToReturn;
} //=======================


/** Tell how many Workers are in this WorkerList. */

public int size() // in WorkerList
{ return itsSize;
} //======================


/** Return a String value representing the entire WorkerList.
* It has one Worker's toString() value on each line. */

public String toString() // in WorkerList
{ String valueToReturn = "";
for (int k = 0; k < itsSize; k++)
valueToReturn += itsItem[k].toString() + "\n";
return valueToReturn;
} //=======================


/** Put the non-null data just before all Workers at the end
* of the WorkerList that have a larger birth year.
* Precondition: The WorkerList has room for the data. */

public void insertByYear (Worker data) // in WorkerList
{ int year = data.getBirthYear();
int k = itsSize;
for (; k > 0 && itsItem[k - 1].getBirthYear() > year; k--)
itsItem[k] = itsItem[k - 1];
itsItem[k] = data;
itsSize++;
} //=======================


/** Put all the Workers in ascending order of birth year. */

public void sort() // in WorkerList
{ if (itsSize > 1)
{ int save = itsSize;
itsSize = 1;
while (itsSize < save)
insertByYear (itsItem[itsSize]);
}
} //======================
}

public class Network 
{
/** Internal invariant: The sequence of available Nodes is
* itsNode[0][k] for 0 <= k < itsNumNodes. The sequence of
* Nodes that itsNode[0][k] connects to is itsNode[k+1][j]
* for 0 <= j < n for some n <= itsNumNodes. The null value
* comes after the last value of each such sequence. */

private Node [][] itsNode;
private int itsNumNodes;
private java.util.Random randy = new java.util.Random();


/** Return a Position object that produces all nodes 1 at a time. */

public Position nodes()
{ return new Position (itsNode[0]);
} //======================


/** Create a random Network with 6 to 15 Nodes, about half
* blue, and with 3 connections per Node on average. No Node
* connects to itself. This is the only method you need to
* replace if you want to obtain Network data from a file. */

public Network()
{ itsNumNodes = 6 + randy.nextInt (10);
itsNode = new Node [itsNumNodes + 1][itsNumNodes + 1];
for (int k = 1; k <= itsNumNodes; k++)
itsNode[0][k - 1] = new Node ("Node#" + k,
randy.nextInt(2) == 1, itsNode[k]);
decideWhichConnectionsNodesHave();
} //======================


/** Choose about 3 nodes at random for each node to connect to. */

private void decideWhichConnectionsNodesHave()
{ for (int k = 1; k <= itsNumNodes; k++)
{ int j = 0;
for (int conn = 1; conn <= itsNumNodes; conn++)
{ if (randy.nextInt (itsNumNodes - 1) < 3 && conn != k)
{ itsNode[k][j] = itsNode[0][conn - 1];
j++;
}
}
}
} //======================
}

// The following are supplied only to allow Network to compile

public class Position
{
public Position (Node[] list)
{
} //======================
}

public class Node // just so Position will compile
{ public Node (String name, boolean blue, Node[] list)
{
} //======================
}

public class Add
{
/** Print the total of the values in the command line arguments.
Precondition: All arguments are parsable as doubles. */

public static void main (String[ ] args)
{ double total = Double.parseDouble (args[0]);
for (int k = 1; k < args.length; k++)
total += Double.parseDouble (args[k]);
System.out.println ("The total is " + total);
} //=======================
}

public class Queue extends java.util.ArrayList
{
/** Create an empty Queue. */

public Queue()
{ super(); // just to remind you of the default constructor
} //======================


/** Tell whether the queue has no more elements. */

public boolean isEmpty()
{ return size() == 0;
} //======================


/** Remove the value that has been in the queue the longest
* time. Throw an Exception if the queue is empty. */

public Object dequeue()
{ return remove (0);
} //======================


/** Return what dequeue would give, without modifying
* the queue. Throw an Exception if the queue is empty. */

public Object peekFront()
{ return get (0);
} //======================


/** Add the given value to the queue. */

public void enqueue (Object ob)
{ add (ob);
} //======================
}

All information Copyright (c)1999 - 104 Dr. William C. Jones, Jr.
Layout and Design Copyright © Psumonix, LLC. All Rights Reserved.
Last modified Thu, 04 Dec 2003 04:53:22 GMT