first commit

This commit is contained in:
Jose Caban
2025-06-07 01:59:34 -04:00
commit 388ac241f0
3558 changed files with 9116289 additions and 0 deletions

214
CS1322/p3/FileChanger.java Normal file
View File

@@ -0,0 +1,214 @@
/**
* <PRE>
* FileChanger.java
*
* Revisions: 1.0 Oct. 05, 2002
* Created the FileChanger class
* 1.1 Oct. 06, 2002
* Compiled, Commented
* 2.0 Oct. 06, 2002
* Deleted all, start from scratch, clean up code
* 2.1 Oct. 06, 2002
* Completed classes
* 2.2 Oct. 06, 2002
* Commented
* </PRE>
*
* Collaboration Statement:
* I worked on the homework assignment alone, using only
* course materials.
*
* Created with JCreatorLE, some indents are off when viewed through notepad
* or EMACS
*
* @author <A HREF="mailto:gtg184g@mail.gatech.edu">Jose Manuel Caban</A>
* @version Version 2.2, Oct. 06, 2002
*/
import java.io.*;
public class FileChanger {
//variables
private String strFileName;
//readers and writers
FileInputStream fis;
ObjectInputStream ois;
FileOutputStream fos;
ObjectOutputStream oos;
public static final boolean bDebug = false; //there's nothing to debug
//that bDebug can handle
////////////////
//Constructors//
////////////////
/**
*Constructor for FileChanger
*@param strFileName the name to be given to the output file
*/
public FileChanger(String strFileName){
this.strFileName = strFileName;
}
////////////////////////////
//Initializers/Destructors//
////////////////////////////
/**
*Initialize the reader streams
*@return true if successful, false if file not found
*/
public boolean initReader(){
//init file input stream
try{
fis = new FileInputStream(strFileName);
}
catch(FileNotFoundException fnfe){
return false;
}
//init obj input stream
try{
ois = new ObjectInputStream(fis);
}
catch(IOException ioe){
return false;
}
return true;
}
/**
*Initialize the write streams
*/
public void initWriter(){
//init file output stream
try{
fos = new FileOutputStream(strFileName);
}
catch(FileNotFoundException fnfe){
System.err.println("File not Found! - initWriter()");
}
//init obj output stream
try{
oos = new ObjectOutputStream(fos);
}
catch(IOException ioe){
System.err.println("IOException - initWriter()");
}
}
/**
*Close read streams
*/
public void closeRead(){
try{
fis.close();
}
catch(IOException ioe){
System.err.println("IOException - closeRead()");
}
}
/**
*Close write streams
*/
public void closeWrite(){
try{
oos.flush();
}
catch(IOException ioe){
System.err.println("IOException - flush objstream - closeWrite()");
}
try{
fos.close();
}
catch(IOException ioe){
System.err.println("IOException - close filestream - closeWrite()");
}
}
///////////
//Methods//
///////////
/**
*Retrieve the next object in the file
*/
public Object nextObject(){
try{
return ois.readObject();
}
catch(EOFException eof){
return null;
}
catch(ClassNotFoundException cnfe){
System.err.println("Class not found - nextObject()");
return null;
}
catch(IOException ioe){
System.err.println("IO Exception - nextObject()");
return null;
}
catch(NullPointerException npe){
System.err.println("Null Pointer Exception - nextObject()");
return null;
}
}
/**
*Write an Object to the file
*@param toWrite, the object to be written
*/
public void writeObject(Object toWrite){
try{
oos.writeObject(toWrite);
}
catch(IOException ioe){
System.err.println("IO Exception - writeObject()");
}
}
/**********************************************************/
/**
* Debugging main for class FileChanger.
* This method will rigorously test my code.
*
* <br><br>
* @param args a String array of command line arguments.
*/
public static void main(String[] args) {
FileChanger fg = new FileChanger("This stinks.txt");
fg.initReader();
fg.initWriter();
fg.writeObject(new Integer(7));
fg.writeObject(new Integer(6));
fg.writeObject(new String("Bob is a person too"));
fg.writeObject(new Boolean(false));
System.out.println(fg.nextObject());
System.out.println(fg.nextObject());
System.out.println(fg.nextObject());
System.out.println(fg.nextObject());
System.out.println(fg.nextObject());
fg.closeRead();
fg.closeWrite();
}// end of main(String[] args)
}// end of class FileChanger

150
CS1322/p3/HashNode.java Normal file
View File

@@ -0,0 +1,150 @@
/**
* <PRE>
* HashNode.java
*
* Revisions: 1.0 Oct. 06, 2002
* Created the HashNode class
* 1.1 oCT. 06, 2002
* Compiled, Tested, Commented
*
* </PRE>
*
* Collaboration Statement:
* I worked on the homework assignment alone, using only
* course materials.
*
* Created with JCreatorLE, some indents are off when viewed through notepad
* or EMACS
*
* @author <A HREF="mailto:gtg184g@mail.gatech.edu">Jose Manuel Caban</A>
* @version Version 1.1, Oct. 06, 2002
*/
public class HashNode {
private HashNode next;
private Object key ;
private Object data;
public static final boolean bDebug = false; //there's nothing to debug
//that bDebug can handle
////////////////
//Constructors//
////////////////
/**
*Constructor for HashNode
*@param key, the object to be stored as the key
*@param data, the object to be stored as data
*/
public HashNode(Object key, Object data){
this.key = key ;
this.data = data;
}
///////////////////////
//Accessors/Modifiers//
///////////////////////
/**
*Modifier for next
*@param next, the next HashNode
*/
public void setNext(HashNode next){
this.next = next;
}
/**
*Accessor for next
*@return the next HashNode
*/
public HashNode getNext(){
return next;
}
/**
*Modifier for key
*@param key, the new value for key
*/
public void setKey(Object key){
this.key = key;
}
/**
*Accessor for key
*@return the value of key
*/
public Object getKey(){
return key;
}
/**
*Modifier for data
*@param data, the new value for data
*/
public void setData(Object data){
this.data = data;
}
/**
*Accessor for data
*@return the value of data
*/
public Object getData(){
return data;
}
///////////
//Methods//
///////////
/**
*Equals method for HashNode
*@return true if both HashNodes have the same key
*/
public boolean equals(Object obj){
if(!(obj instanceof HashNode)){
return false;
}
HashNode hTemp = (HashNode)obj;
if(hTemp.getData().equals(this.data)){
return true;
}
return false;
}
public String toString(){
return (data.toString());
}
/*************************************************************/
/**
* Debugging main for class HashNode.
* This method will rigorously test my code.
*
* <br><br>
* @param args a String array of command line arguments.
*/
public static void main(String[] args) {
HashNode dooby = new HashNode("key","data");
HashNode stinky = new HashNode("key","data");
System.out.println(dooby.equals(stinky));
stinky.setKey(new Integer(6));
stinky.setData("key");
stinky.setNext(dooby);
System.out.println(dooby.equals(stinky));
System.out.println(stinky.getKey());
System.out.println(stinky.getData());
System.out.println(stinky.getNext().getKey());
}// end of main(String[] args)
}// end of class HashNode

337
CS1322/p3/HashTable.java Normal file
View File

@@ -0,0 +1,337 @@
/**
* <PRE>
* HashTable.java
*
* Revisions: 1.0 Oct. 06, 2002
* Created the HashTable class
* 1.1 Oct. 10, 2002
* Compiled, finished, Commented
*
* </PRE>
*
* Collaboration Statement:
* I worked on the homework assignment alone, using only
* course materials.
*
* Created with JCreatorLE, some indents are off when viewed through notepad
* or EMACS
*
* @author <A HREF="mailto:gtg184g@mail.gatech.edu">Jose Manuel Caban</A>
* @version Version 1.0, Oct. 06, 2002
*/
typedef struct HashNode
{
HashNode* next;
int key;
int data;
};
HashNode[] hTable;
////////////////
//Constructors//
////////////////
public HashTable(int size)
{
hTable = new HashNode[size];
}
///////////
//Methods//
///////////
/**
*add data to a given location
*@param data added to location key
*@param key, the location to store data
*/
public void add(Object key, Object data)
{
int iKey = Math.abs(key.hashCode()) % hTable.length;
if(hTable[iKey] == null)
{
hTable[iKey] = new HashNode(key,data);
}
else
{
HashNode temp = new HashNode(key,data);
temp.setNext(hTable[iKey]);
hTable[iKey] = temp;
}
}
/**
*@return the data located
*@param key
*/
public Object get(Object key)
{
int iKey = Math.abs(key.hashCode()) % hTable.length;
if(hTable[iKey] == null)
{
return null;
}
HashNode current = hTable[iKey];
while(current != null)
{
if(current.getKey().equals(key))
{
return current.getData();
}
current = current.getNext();
}
return null;
}//end get(@key)
/**
*Remove hashNode at key and return data
*@param key, the node to be removed
*/
public Object remove(Object key)
{
int iKey = Math.abs(key.hashCode()) % hTable.length;
if(hTable[iKey] == null)
{
return null;
}
HashNode current = hTable[iKey];
if(current.getKey().equals(key))
{
hTable[iKey] = current.getNext();
return current.getData();
}
else
{ //if(the list is long and annoying)
//set predefs
HashNode hPrev = current; //a little longer and its hPrevInstance
current = current.getNext();
while(current != null)
{
if(current.getKey().equals(key))
{
hPrev.setNext(current.getNext());
return current.getData();
}
current = current.getNext();
hPrev = hPrev.getNext();
}
return null;
}
}//end remove(@key)
/**
*@return enumeration of of HashTable
*/
public Enumeration elements()
{
Vector vTemp = new Vector();
HashNode hCurr;
for(int i=0; i<hTable.length; i++)
{
hCurr = hTable[i];
while(hCurr != null)
{
vTemp.add(hCurr.getData());
hCurr = hCurr.getNext();
}
}
return vTemp.elements();
}
/**
*Rehash Hashtable to iSize
*@param iSize, size to be resized to
*/
public void rehash(int iSize)
{
//by the way, I like the fact we're using Hungarian notation now;
//Microsoft is more useful than the LUG@GATECH would like to think :)
//did I already say this in Zoo.java?
//don't waste CPU cycles
if(hTable.length == 0)
{
hTable = new HashNode[iSize];
return;
}
HashNode[] hTemp = new HashNode[hTable.length];
for(int i=0; i<hTable.length; i++)
{
hTemp[i] = hTable[i];
}
//define cars needed
hTable = new HashNode[iSize];
HashNode hCurr;
for(int i=0; i<hTemp.length; i++)
{
hCurr = hTemp[i];
while(hCurr != null)
{
add(hCurr.getKey(),hCurr.getData());
hCurr = hCurr.getNext();
}
}
}//end rehash(int)
/**
*@return size of the hashtable
*/
public int size()
{
return hTable.length;
}
/**
*@return String version of Hashtable
*/
public String toString()
{
String reallyLong = "";
HashNode hCurr;
for(int i=0; i<hTable.length; i++)
{
hCurr = hTable[i];
while(hCurr != null)
{
reallyLong += hCurr.getData().toString() + "\n";
hCurr = hCurr.getNext();
}
}
return reallyLong;
}
/**
*Adds x elements to the HashTable
*!!!Meant for Debugging only!!!
*/
public void addRandom(int iHowMany)
{
//you know this was fairly creative
//I believe this deserves extra credit
//or at least send me money
for(int i=0; i<iHowMany; i++)
{
//this will force fast systems like mine to have
//a different value near every iteration
//hell, handling a 3D matrix in Java even caused some delay
//on my dual mp2100+, what an inefficient VM sun makes :(
//I was going to multithread this, one thread adding 2 starting at
//zero, the other adding 2 starting at 1, but then I got lazy...
int[][][] hehehe = new int[100][100][100];
for(int x=0; x<100; x++)
{
for(int y=0; y<100; y++)
{
for(int z=0; z<100; z++)
{
hehehe[x][y][z] = 1;
}
}
}
hehehe = new int[1][1][1];
//end
switch((int)(System.currentTimeMillis() % 10))
{
case 0:
add(new Integer((int)(System.currentTimeMillis()%10)),
new Integer(6));
break;
case 1:
add(new Integer((int)(System.currentTimeMillis()%10)),
new Mail("HAHA","HA","Joe"));
break;
case 2:
add(new String("Fido"),new Integer(2));
break;
case 3:
add(new String("Alfonso"),new Integer(45));
break;
case 4:
add(new Double(3.14),new Float(3.14));
break;
case 5:
add(new Integer(43),new Float(6));
break;
case 6:
add(new String("This"),new String("is"));
break;
case 7:
add(new String("getting"),new String("way"));
break;
case 8:
add(new String("too"),new String("long"));
break;
case 9:
add(new String("ha"),new String("laziness"));
break;
default:
break;
}
}
}//end addRandom(int)
/****************************************************************/
/**
* Debugging main for class HashTable.
* This method will rigorously test my code.
*
* <br><br>
* @param args a String array of command line arguments.
*/
public static void main(String[] args)
{
HashTable hashey = new HashTable(5);
//test add
hashey.addRandom(15);
System.out.println(hashey);
hashey = new HashTable(5);
hashey.addRandom(12);
System.out.println("Testing elements");
Enumeration e = hashey.elements();
while(e.hasMoreElements())
{
System.out.println(e.nextElement());
}
//hehehehehehhehehe, lets test this sucker for REAL
//don't try this at home :)
//approx. runtime on a Tiger MPX dual MP2100+ 1.5GB RAM
//thats 100% CPU utilaztion at 1.733GHz IPC3
//around 60 seconds (im guessing)
//:)
hashey = new HashTable(200);
hashey.addRandom(2000);
System.out.println(hashey);
}// end of main(String[] args)
}// end of class HashTable

134
CS1322/p3/IOHelp.txt Normal file
View File

@@ -0,0 +1,134 @@
This is a walkthrough of how to use File I/O. It will give a walkthrough of
how to read from standard in, and how to read from and write to files.
WRITING AND READING TO FILES
============================================================================
/O stands for "input and output." File I/O is reading from or writing to
files on the disk. It should be noted that java treats network
sockets like files as far as IO goes, like UNIX does. Although networking
is not covered in this class, it is quite similar to accessing files on
the disk. The standard input, standard error, and standard output are
also very similar to files, and in fact the types for these three streams
are found in java.io, along with the classes to perform other file operations.
There are many slight variations in what needs to be done to perform
File IO depending on what type of file is being dealt with and what needs
to be done with it. We will first focus our attention on reading lines from
a text file. The first thing that we should do is open the file in a
FileReader (Note that we are creating a FileReader object):
FileReader fr= new FileReader("myFile.txt");
The next thing that we should do is to wrap the FileReader in a
BufferedReader:
BufferedReader br= new BufferedReader(fr);
This code creates a BufferedReader which will ask fr what is in the file
and return it to the program line by line.
The designers of Java decided to use this wrapper class concept to allow a
lot of flexibility without having to create hundreds of different classes.
Sometimes people will accomplish the above in one statement where perhaps
the "wrapper" idea will be more obvious:
BufferedReader has, among other methods, the method
String readLine()
which returns the next line of text from the file without the '\n' on the
end- this method also automatically goes to the next line, so the next
call to readLine() will give the next line, not the same one. When
the program is done reading from the file, it should call the close method
on the BufferedReader (which will close the underlying FileReader) so
that the associated file resources may be freed (note that while
memory is garbage collected, other resources, such as file descriptors
are not). The above code, must of course have the exceptions dealt with
properly, but that will be discussed in a minute.
The other major operation that we will concern ourselves with is writing
lines of text to a file. This can be accomplished similarly via the
use of the FileWriter and PrintWriter classes:
FileWriter fr=new FileWriter("output.txt");
PrintWriter pr= new PrintWriter(fr);
The PrintWriter class has print() and println() methods which are overloaded
to accept just about any paramter type and write it to the underlying
FileWriter. It should be noted that print and println do NOT throw
exceptions if a problem occurs while writing to the underlying file-
instead, they just set an error variable in the PrintWriter instance,
which may be checked with the checkError() method. The FileWriter class,
may throw an exception when created, as described later. The PrintWriter
must also be closed when the program is finished with it. If an output
stream in not closed, then not only will the resources not be freed,
but also, the data will never actually be written out to the disk,
as it is buffered in memory, and flushed only when a certain amount
is present, or the close() or flush() method gets called.
So why do we need to deal with these extra classes? Why can't we
just have one class to do it all? And how do these classes interact?
Each class does a specific job and provides a certain ammount of modularity
and abstraction. Lets look at the FileReader and BufferedReader:
FileReader- has the job of reading characters from a file and
assumes that the characters use default encoding.
BufferedReader- has the job of reading text from a character-input stream,
buffering characters so as to provide for the efficient
reading of characters, arrays, and lines.
there are other classes that could be put into a BufferedReader, for example,
an InputStreamReader- which basically reads from a byte stream and converts
to a character stream, using some encoding scheme, which may be specified.
So for example, if the file that you wanted to read used a different Unicode
encoding scheme than the default for your system (maybe you are writing
some international buisness software), then you would instead need to
make a FileInputStream, wrap that in an InputStreamReader, then wrap that
in a BufferedReader. In general, "Stream" deals with bytes, whereas
"Reader" deals with characters.
This abstraction gives the input classes more flexibility, in that
they can also be used to allow for reading from other input streams
than those avaiable from files on the disk- a network connection
provides an instance of InputStream to read incoming data from
the connection- InputStreams (as just mentioned) deal with bytes-
if the program wants to read lines of text, for example, the same
wrapping can be performed with the same classes to get a BufferedReader
to give lines of text at a time from the network
WRITING AND READING OBJECTS TO FILES
============================================================================
Writing and reading java objects to a file are slightly different than writing
and reading Strings to file. First off, in order for a java Object to be able
to be written to a file, it must implement Serializable. Only classes which
implement the Serializable interface can be written to a file as an Object.
To write an object to a file, you first need to create the Streams.
The reason that you cannot use PrintWriter as you used before is because
PrintWriter only can write Strings to a file.
The two streams that need to be created are
FileOutputStream and ObjectOutputStream.
The constructor to FileOutputStream takes in the name of the file to write to as
a String. If the file does not exist, it creates one.
The constructor to ObjectOutputStream takes in the newly created
FileOutputStream.
After creating them, you can write the object to the ObjectOutputStream.
If the ObjectOutputStream was called oos, then oos.writeObject(theObject);
would write the object to file.
After writing all object, make sure to flush the ObjectOutputStream and close
the FileOutputStream.
To read objects from a file, you need to create an ObjectInputStream and a
FileInputStream. The constructors for these work similar to the writer.
To actually read an object, do ois.readObject(). This will need to be casted
to the actuall object that it is. If the file does not exist, it will throw
a FileNotFoundException. When the end of the file is reached, it throws
an EndOfFileException.

138
CS1322/p3/Mail.java Normal file
View File

@@ -0,0 +1,138 @@
/**
* <PRE>
* Mail.java
*
* Revisions: 1.0 Oct. 01, 2002
* Created the Mail class
* 1.1 Oct. 05, 2002
* Finished, Compiled, Commented
*
* </PRE>
*
* Collaboration Statement:
* I worked on the homework assignment alone, using only
* course materials.
*
* Created with JCreatorLE, some indents are off when viewed through notepad
* or EMACS
*
* @author <A HREF="mailto:gtg184g@mail.gatech.edu">Jose Manuel Caban</A>
* @version Version 1.1, Oct. 01, 2002
*/
public class Mail implements P3Type{
public static final boolean bDebug = false; //there's nothing to debug
//that bDebug can handle
private String strFrom;
private String strTo;
private String strMessage;
////////////////
//Constructors//
////////////////
/**
*Constructor for mail
*@param strMessage, the message value
*@param strFrom, who sent the message
*@param strTo, who the message will be sent to
*/
public Mail(String strMessage, String strFrom, String strTo){
//I prefer to use the this. references for the constructors
//rather than referencing the accessor/modifiers
//either way is correct according to lecture, its just
//a matter of just how encapsulated it should be
this.strMessage = strMessage;
this.strFrom = strFrom;
this.strTo = strTo;
}//end Mail(message,from,to)
///////////////////////
//Accessors/Modifiers//
///////////////////////
/**
*Modifier for strFrom
*@param strFrom the value to set this.strFrom to
*/
public void setStrFrom(String strFrom){
this.strFrom = strFrom;
}
/**
*Accessor for strFrom
*@return value of strFrom
*/
public String getStrFrom(){
return strFrom;
}
/**
*Modifier for strTo
*@param strTo, the value to set for this.strTo
*/
public void setStrTo(String strTo){
this.strTo = strTo;
}
/**
*Accessor for strTo
*@return the value of strTo
*/
public String getStrTo(){
return strTo;
}
/**
*Modifier for strMessage
*@param strMessage the value to set this.strMessage to
*/
public void setStrMessage(String strMessage){
this.strMessage = strMessage;
}
/**
*Accessor for strMessage
*@return the value of strMessage
*/
public String getStrMessage(){
return strMessage;
}
///////////
//Methods//
///////////
public String toString(){
return ("To: " + strTo + "\nFrom: " + strFrom +
"\nMessage: " + strMessage);
}
/******************************************************/
/**
* Debugging main for class Mail.
* This method will rigorously test my code.
*
* <br><br>
* @param args a String array of command line arguments.
*/
public static void main(String[] args) {
Mail box = new Mail("Screw You","Bob","Rob");
System.out.println(box);
box.setStrMessage("I love you");
box.setStrFrom("Rob");
box.setStrTo("Bob");
System.out.println(box);
System.out.println(box.getStrTo());
System.out.println(box.getStrFrom());
System.out.println(box.getStrMessage());
}// end of main(String[] args)
}// end of class Mail

191
CS1322/p3/MailBox.java Normal file
View File

@@ -0,0 +1,191 @@
/**
* <PRE>
* MailBox.java
*
* Revisions: 1.0 Oct. 01, 2002
* Created the MailBox class
* 1.1 Oct. 05, 2002
* Compiled, Finished, Commented
*
* </PRE>
*
* Collaboration Statement:
* I worked on the homework assignment alone, using only
* course materials.
*
* Created with JCreatorLE, some indents are off when viewed through notepad
* or EMACS
*
* @author <A HREF="mailto:gtg184g@mail.gatech.edu">Jose Manuel Caban</A>
* @version Version 1.1, Oct. 05, 2002
*/
import java.util.Vector;
import java.util.Enumeration;
public class MailBox implements P3Type{
public static final boolean bDebug = false; //there's nothing to debug
//that bDebug can handle
private String strLName;
private String strFName;
private Vector vMail;
////////////////
//Constructors//
////////////////
/**
*Constructor for MailBox
*@param last the value for strLName
*@param first the value for strFName
*/
public MailBox(String last, String first){
strLName = last;
strFName = first;
vMail = new Vector();
}
///////////////////////
//Accessors/Modifiers//
///////////////////////
/**
*Modifier for strLName
*@param strLName the value to set this.strLName
*/
public void setStrLName(String strLName){
this.strLName = strLName;
}
/**
*Accessor for strLName
*@return the value of strLName
*/
public String getStrLName(){
return strLName;
}
/**
*Modifier for strFName
*@param strFName the value to set this.strFName
*/
public void setStrFName(String strFName){
this.strFName = strFName;
}
/**
*Accessor for strFName
*@return the value of strFName
*/
public String getStrFName(){
return strFName;
}
///////////
//Methods//
///////////
/**
*Adds mail to the persons box
*@param mail, the mail to be added
*/
public void addMail(Mail mail){
vMail.add(mail);
}
/**
*clear vector and return enumeration of all mail
*@return an enumeration of the mail a person has
*/
public Enumeration getMail(){
Vector vTemp = (Vector)vMail.clone();
Enumeration enum = vTemp.elements();
vMail.clear();
return enum;
}
/**
*toString() override
*@return the amount of mail the person has as a string
*/
public String toString(){
return (getStrFName() + " " + getStrLName() + " has " + vMail.size() +
" piece" + (vMail.size()==1?"":"s") +
/*I used ==1 because when its 0 it should be pieces not piece*/
" of mail.");
}
/**
*@return true if both Mailboxes are owned by the same person
*/
public boolean equals(Object obj){
if(!(obj instanceof MailBox)){
return false;
}
MailBox temp = (MailBox)obj;
if(!(this.getStrFName().equals(temp.getStrFName()))){
return false;
}
if(!(this.getStrLName().equals(temp.getStrLName()))){
return false;
}
return true;
}
/*******************************************************/
/**
* Debugging main for class MailBox.
* This method will rigorously test my code.
*
* <br><br>
* @param args a String array of command line arguments.
*/
public static void main(String[] args) {
MailBox box1 = new MailBox("Romero" , "John");
MailBox box2 = new MailBox("Carmack" , "John");
MailBox box3 = new MailBox("Sweeney" , "Tim" );
//just for reference
//Mail(String strMessage, String strFrom, String strTo)
//
Mail mail1 = new Mail("Don't Screw up Doom3","Gamers","John Carmack");
Mail mail2 = new Mail("Man you screwed up Daikatana","The World","Romero");
Mail spammail;
spammail=new Mail("Buy out product!!!!!","Crappy Company","MailBox owner");
box1.addMail(mail2);
box2.addMail(mail1);
box3.addMail(spammail);
System.out.println(box1);
box1 = new MailBox("Carmack","John");
System.out.println(box1.equals(box2));
box2.addMail(spammail);
box2.addMail(new Mail("This sucks","Me","you"));
System.out.println(box2);
Enumeration e = box2.getMail();
System.out.println("\nStart Elements\n");
while(e.hasMoreElements()){
System.out.println(e.nextElement());
}
System.out.println();
System.out.println(box2.equals(box3));
}// end of main(String[] args)
}// end of class MailBox

368
CS1322/p3/Manager.java Normal file
View File

@@ -0,0 +1,368 @@
/**
* <PRE>
* Manager.java
*
* Revisions: 1.0 Oct. 11, 2002
* Created the Manager class
* 1.1 Oct. 16, 2002
* Compiled, Commented, Finished
* 1.2 Oct. 17, 2002
* Corrected Last Name only being shown on to and from for mail
* 1.3 Oct. 17, 2002
* Corrected infinite loop if letter entered in CcustomerHere()
* 2.0 Oct. 17, 2002
* Added some comments to make what I did clearer as well
* as made certain aspects of the code "better"
* 2.1 Oct. 18, 2002
* Fixed a Comment in readText()
*
* </PRE>
*
* Collaboration Statement:
* I worked on the homework assignment alone, using only
* course materials.
*
* Created with JCreatorLE, some indents are off when viewed through notepad
* or EMACS
*
* @author <A HREF="mailto:gtg184g@mail.gatech.edu">Jose Manuel Caban</A>
* @version Version 2.1, Oct. 18, 2002
*/
import java.io.*;
import java.util.*;
public class Manager implements P3Type{
public static final boolean bDebug = false;
//declaration of globals
private String strCustFName ;
private String strCustLName ;
private PostOffice objPostOffice = new PostOffice();
private BufferedReader KB_IN;
////////////////
//Constructors//
////////////////
/*
This constructor would have been used if readFile() wasn't run on every
run of managerActions(). Having the constructor read the file and then
waiting to write it after the program is done would mean any mailbox
deleted from the PostOffice would not be removed from the file and in
case of system failure, when the RAM is flushed the deleted mailboxes would
never actually be deleted.
public Manager(){
readFile();
}
*/
///////////
//Methods//
///////////
/**
*Initialize the Keyboard input
*/
private void initInput(){
KB_IN = new BufferedReader(new InputStreamReader(System.in));
}
/**
*Read contents of MyPO
*/
private void readFile(){
FileChanger fc = new FileChanger(P3Type.POST_OFFICE);
boolean truth = fc.initReader();
Object temp;
if(truth != false){
do{
temp = fc.nextObject();
if(temp != null){
objPostOffice.issue((MailBox)temp);
}
}while(temp != null);
fc.closeRead();
}
}//end readFile()
/**
*Read Input
*/
private Object[] readText(String KB_INPUT,int KB_INPUT_PARSE){
boolean trust = true;
//do..while() for purposes of keeping the code running until\
//an acceptable value is entered
do{
try{
KB_INPUT = KB_IN.readLine();
}
catch(IOException ioe){
System.err.println("IOException in readText()");
}
try{
KB_INPUT_PARSE = Integer.parseInt(KB_INPUT);
trust = true;
}
catch(NumberFormatException nfe){
System.err.println("Please enter a number next time");
trust = false;
}
}while(trust != true);
//set-up return array
Object[] toReturn = new Object[2];
toReturn[0] = KB_INPUT;
toReturn[1] = new Integer(KB_INPUT_PARSE);
return toReturn;
}//end readText(String,int)
/**
*Perform actions as the manager
*@return false if done
*/
public boolean managerActions(){
//A Note: if the readFile() function/code is run everytime
//managerActions() is run, then the file must be rewritten everytime
//a mailbox is deleted. This is good and bad, good for performance
//bad in case of a crash
//I opted for the lesser performance but better reliability
//we don't want the mailboxes people deleted reappearing in case of
//system failure do we?
readFile();
System.out.println("\n"+P3Type.INIT_ACTIONS);
//let's keep this archane Hungarian Style Notation, shall we?
String KB_INPUT = "";
int KB_INPUT_PARSE = 0;
initInput(); //I also moved this for cleanliness
//In order to lessen the clutter of this code, I created a separate
//function to handle the text input
Object[] temp = readText(KB_INPUT,KB_INPUT_PARSE);
KB_INPUT = (String)temp[0];
Integer tucow = (Integer)temp[1];
KB_INPUT_PARSE = tucow.intValue();
switch(KB_INPUT_PARSE){
case 1:
if(bDebug == true){
System.out.println("Case " + KB_INPUT_PARSE);
}
boolean trueness = true;
do{
System.out.println("Please enter the Customer's name");
try{
KB_INPUT = KB_IN.readLine();
}
catch(IOException ioe){
System.err.println("IOException in managerAction()"+
" when trying to readLine().");
}
trueness = customerHere(KB_INPUT);
}while(trueness);
break;
//end case 1
case 2:
if(bDebug == true){
System.out.println("Case " + KB_INPUT_PARSE);
}
System.out.print("Adding Rooms: ");
objPostOffice.resize();
System.out.println("Done.");
break;
//end case 2
case 3:
if(bDebug == true){
System.out.println("Case " + KB_INPUT_PARSE);
}
System.out.println("The current boxes are: ");
Enumeration e = objPostOffice.allBoxes();
if(e != null){
while(e.hasMoreElements()){
System.out.println(e.nextElement());
}
}
break;
//end case 3
case 0:
if(bDebug == true){
System.out.println("Case " + KB_INPUT_PARSE);
}
objPostOffice.leavingForTheDay();
return false;
//end case 0
default:
if(bDebug == true){
System.out.println("Case " + KB_INPUT_PARSE);
}
System.out.println("You didn't input 0-3 did you?");
return managerActions(); //restart
//end default
}
return true;
}//end managerActions()
/**
*Customer Actions
*@return false when done
*/
public boolean customerHere(String strName){
for(;;){
System.out.println("\n"+P3Type.CUST_HERE);
initInput();
String KB_INPUT = "";
int KB_INPUT_PARSE = 0;
//In order to lessen the clutter of this code, I created a separate
//function to handle the text input
Object[] temp = readText(KB_INPUT,KB_INPUT_PARSE);
KB_INPUT = (String)temp[0];
Integer tucow = (Integer)temp[1];
KB_INPUT_PARSE = tucow.intValue();
/*get names*/
StringTokenizer st = new StringTokenizer(strName);
strCustFName = st.nextToken();
while(st.hasMoreTokens()){
strCustLName = st.nextToken();
}
/////////////
switch(KB_INPUT_PARSE){
case 1:
if(bDebug == true){
System.out.println("Case " + KB_INPUT_PARSE);
}
MailBox objNewBox = new MailBox(strCustLName,strCustFName);
objPostOffice.issue(objNewBox);
objPostOffice.leavingForTheDay(); //rewrites mailbox list
break;
//end case 1
case 2:
if(bDebug == true){
System.out.println("Case " + KB_INPUT_PARSE);
}
int iValue = objPostOffice.remove(strCustLName);
if(iValue == -3){
System.out.println(P3Type.NO_MAILBOX);
}
else{ //if(iValue >= 0)
System.out.println(P3Type.NUM_TELEGRAMS + iValue);
objPostOffice.leavingForTheDay(); //rewrites mailbox list
}
break;
//end case 2
case 3:
if(bDebug == true){
System.out.println("Case " + KB_INPUT_PARSE);
}
String LName = "";
String FName = "";
String message ="";
int iVal;
System.out.println("Who do you want to send the message to?");
try{
KB_INPUT = KB_IN.readLine();
}
catch(IOException ioe){
System.err.println("IOException READLine() in case3"+
"@ customerHere()");
}
st = new StringTokenizer(KB_INPUT);
FName = st.nextToken();
while(st.hasMoreTokens()){
LName = st.nextToken();
}
System.out.println("What is the message?");
try{
message = KB_IN.readLine();
}
catch(IOException ioe){
System.err.println("Error in case3 readLine() message" +
"@ customerHere()");
}
Mail objNewMail = new Mail(message,strCustFName+
" "+strCustLName,FName+" "+LName);
iVal = objPostOffice.send(objNewMail);
if(iVal == P3Type.BAD_SENDER){
System.out.println("You need to open a mailbox " +
"with us first.");
}
else if(iVal == P3Type.NO_RECIPIENT){
System.out.println("The person you are trying " +
"to send to doesn't have a " +
"mailbox here.");
}
else {//if(message.equals(P3Type.MAIL_SENT))
System.out.println("Mail sent successfully, please allow" +
" 6 to 8 weeks for delivery.");
}
break;
//end case 3
case 4:
if(bDebug == true){
System.out.println("Case " + KB_INPUT_PARSE);
}
System.out.println(objPostOffice.retrieve(strCustLName));
break;
case 0:
if(bDebug == true){
System.out.println("Case " + KB_INPUT_PARSE);
}
return false;
default:
if(bDebug == true){
System.out.println("Case " + KB_INPUT_PARSE);
}
System.out.println("Didn't enter 0-4, try again");
return customerHere(strName); //restart
}//end switch
}//end for(;;)
}//end customerHere(String)
/**
* Debugging main for class Manager.
* This method will rigorously test my code.
*
* <br><br>
* @param args a String array of command line arguments.
*/
public static void main(String[] args) {
Manager Bob = new Manager();
Bob.managerActions();
}// end of main(String[] args)
}// end of class Manager

BIN
CS1322/p3/MyPO Normal file

Binary file not shown.

47
CS1322/p3/P3.java Normal file
View File

@@ -0,0 +1,47 @@
/**
* <PRE>
* P3.java
*
* Revisions: 1.0 Oct. 16, 2002
* Created the P3 class
* 1.1 Oct. 16, 2002
* Compiled, Finished, Done
*
* </PRE>
*
* Collaboration Statement:
* I worked on the homework assignment alone, using only
* course materials.
*
* Created with JCreatorLE, some indents are off when viewed through notepad
* or EMACS
*
* @author <A HREF="mailto:gtg184g@mail.gatech.edu">Jose Manuel Caban</A>
* @version Version 1.1, Oct. 16, 2002
*/
public class P3 {
/**
* Debugging main for class P3.
* This method will rigorously test my code.
*
* <br><br>
* @param args a String array of command line arguments.
*/
public static void main(String[] args) {
Manager manager = new Manager();
boolean truthitude = true;
do{
truthitude = manager.managerActions();
}while(truthitude != false);
System.out.println(P3Type.GOOD_BYE);
}// end of main(String[] args)
}// end of class P3

69
CS1322/p3/P3Type.java Normal file
View File

@@ -0,0 +1,69 @@
/**
* P3Type.java
* This interface will be used to hold constants for P3.
* It extends Serializable so that classes which implement this interface
* can be saved to a file
*
* Created: Fri Aug 02 11:45:48 2002
*
* @author <a href="mailto:bsbeck@cc.gatech.edu "> Brandon Beck </a>
* @version 1.0
*/
import java.io.*;
public interface P3Type extends Serializable
{
// This variable holds the default size of the hash table.
public static final int DEFAULT_SIZE = 10;
// This variable holds a constant String saying that a person has never
// been issued a mailbox before
public static final String NO_MAILBOX = "The current customer "
+ "has never been issued a mailbox before!";
// This variable represents that the person trying to send the mail
// does not have a mailbox
public static final int BAD_SENDER = -1;
// This variable represents that the person the mail is sent to
// does not have a mailbox
public static final int NO_RECIPIENT = -2;
// This variable represents that the mail was sent successfully
public static final int MAIL_SENT = 1;
// This variable holds a constant int representing that a person has not
// been issued a mailbox before
public static final int NO_MAILBOX_NUM = -3;
// This variable holds a String telling the customer how many of his
// telegrams got thrown away when he closed his mailbox
public static final String NUM_TELEGRAMS = "The number of unread " +
"telegrams when you closed your mailbox was ";
// This will be the String constant of the initial menu. These are the
// initial actions that a manager of the PostOffice can perform.
public static final String INIT_ACTIONS =
"1) Help Customer \n" +
"2) Add More Rooms \n" +
"3) View All MailBoxes \n" +
"0) Leave for the Day \n";
// This will be the String constant of the customer menu. These are the
// actions of a customer
public static final String CUST_HERE =
"1) I want a mailbox at this post office. \n" +
"2) I no longer want a post office at this mailbox. \n" +
"3) I want to send a telegram. \n" +
"4) I want to read all of the telegrams I have received. \n" +
"0) Okay, I am done. \n";
// This is a string representing the file to save the Post Office to
public static final String POST_OFFICE = "MyPO";
// This is a string saying goodbye to the manager
public static final String GOOD_BYE = "See you tomorrow";
} // end P3Type

237
CS1322/p3/PostOffice.java Normal file
View File

@@ -0,0 +1,237 @@
/**
* <PRE>
* PostOffice.java
*
* Revisions: 1.0 Oct. 11, 2002
* Created the PostOffice class
* 1.1 Oct. 11, 2002
* Compiled, Finished, Commented
* 2.0 Oct. 16, 2002
* Added Phase6 methods
*
* </PRE>
*
* Collaboration Statement:
* I worked on the homework assignment alone, using only
* course materials.
*
* Created with JCreatorLE, some indents are off when viewed through notepad
* or EMACS
*
* @author <A HREF="mailto:gtg184g@mail.gatech.edu">Jose Manuel Caban</A>
* @version Version 2.0, Oct. 16, 2002
*/
import java.util.*;
public class PostOffice implements P3Type{
public static final boolean bDebug = false; //nothing to debug via var tho
HashTable htExpress = new HashTable(10);
///////////
//Methods//
///////////
/**
*Issue a mailbox with key as last name
*@param mbToAdd, the mailbox to be added
*/
public void issue(MailBox mbToAdd){
if(htExpress.get(mbToAdd.getStrLName()) == null){ //avoid duplicate
htExpress.add(mbToAdd.getStrLName(),mbToAdd);
}
}
/**
*Return the mail in a given persons box
*@param strLName, the last name of the person
*/
public String retrieve(String strLName){
if(htExpress.get(strLName) == null){
return P3Type.NO_MAILBOX;
}
MailBox mb = (MailBox)htExpress.get(strLName);
Enumeration e = mb.getMail();
String strLong = "";
int count = 1; //for flair
while(e.hasMoreElements()){
strLong += "\nMessage " + count + ":\n" +
e.nextElement().toString() + "\n";
count++;
}
return strLong;
}
/**
*Send mail
*@param toSend, the message to be sent
*/
public int send(Mail toSend){
String strFromLName = "";
String strToLName = "";
StringTokenizer st;
//verify sender
st = new StringTokenizer(toSend.getStrFrom());
while(st.hasMoreTokens()){
strFromLName = st.nextToken();
}
if(htExpress.get(strFromLName) == null){
return P3Type.BAD_SENDER;
}
//verify recipient
st = new StringTokenizer(toSend.getStrTo());
while(st.hasMoreTokens()){
strToLName = st.nextToken();
}
if(htExpress.get(strToLName) == null){
return P3Type.NO_RECIPIENT;
}
//add the mail
MailBox mb = (MailBox)htExpress.get(strToLName);
mb.addMail(toSend);
return P3Type.MAIL_SENT;
}//end send(Mail)
/**
*@param strLName, to be removed from PostOffice
*@return the number of unread messages in the box
*/
public int remove(String strLName){
if(htExpress.get(strLName) == null){
return P3Type.NO_MAILBOX_NUM;
}
int count = 0;
MailBox mTemp = (MailBox)htExpress.remove(strLName);
Enumeration e = mTemp.getMail();
//only because it looks cooler AND takes less typing
for(;e.hasMoreElements();count++,e.nextElement());
return count;
}//end remove(String)
/**
*@return enumeration containing the mailboxes
*/
public Enumeration allBoxes(){
//this is a tough one
//took 4 of the 5 hours of p3phase5
return htExpress.elements();
}
/**
*Resize the HashTable
*Doubles current size
*/
public void resize(){
htExpress.rehash(htExpress.size() * 2);
}
/* */
/*Phase 6*/
/* */
/**
*Write mailboxes to file and close program
*/
public void leavingForTheDay(){
FileChanger fc = new FileChanger(P3Type.POST_OFFICE);
fc.initWriter();
Enumeration e = htExpress.elements();
while(e.hasMoreElements()){
fc.writeObject(e.nextElement());
}
fc.closeWrite();
}
/**********************************************************/
/**
* Debugging main for class PostOffice.
* This method will rigorously test my code.
*
* <br><br>
* @param args a String array of command line arguments.
*/
public static void main(String[] args) {
//System.testclass.for.me
//If Java is so smart, why doesn't it have that!
//by the way, how's that commenting style I just thought of /*stuff*/
/*Begin Test Class*/
PostOffice po = new PostOffice();
//create test dummie...er...beta testers
//game gods
po.issue(new MailBox("Romero","John")); //hmm, two John's maybe
po.issue(new MailBox("Carmack","John")); //I need a name change?
po.issue(new MailBox("Sweeney","Tim"));
po.issue(new MailBox("Miyamato","Shigeru"));
//musical greatness
po.issue(new MailBox("Beethoven","Ludwik von"));//hehe test StringToken too
po.issue(new MailBox("Stravinsky","Igor"));
po.issue(new MailBox("Reznor","Trent"));
po.issue(new MailBox("Bowie","David"));
//good anime characters
po.issue(new MailBox("Starwind","Gene"));
po.issue(new MailBox("Spiegel","Spike"));
//assorted
po.issue(new MailBox("McGee","Mike")); //that's Mike McGee of the IN
po.issue(new MailBox("Dole","Bob")); //viva la Pfiezer!
/*Test Exception*/
po.issue(new MailBox("Romero","John"));
/*Test Retrieve*/
po.send(new Mail("You're career has hit rock bottom","Carmack","Romero"));
po.send(new Mail("I mean games for the PalmPC!?","Sweeney","Romero"));
/*Test Exception*/
if(po.send(new Mail("BOOOOOO","Bob","Romero")) == -1){
System.out.println("BAD_SENDER");
}
//despite not receiving the mail, a response!
if(po.send(new Mail("FU!","Romero","Bob")) == -2){
System.out.println("BAD_RECIPIENT");
}
System.out.println(po.retrieve("Romero"));
/*Test Remove*/
/*Test Exception*/
System.out.println(po.remove("Romreo")); //oops :)
System.out.println(po.remove("Romero"));
/*Nothing to test for resize() and allBoxes(), tested in HashTable*/
/*End Test Class*/
}// end of main(String[] args)
}// end of class PostOffice

BIN
CS1322/p3/Test.txt Normal file

Binary file not shown.

BIN
CS1322/p3/This stinks.txt Normal file

Binary file not shown.

View File

@@ -0,0 +1,100 @@
This file contains a walkthrough on how to use important tools in Java. These
include Vectors, Enumerations and StringTokenizers. All of these classes are
located in the package java.util
VECTORS
===============================================================================
In order to use the Vector class, you need to import java.util.Vector.
Look in the Java API to see a list of all the methods that can be used with
Vectors. The great thing about Vectors is that they are dynamic like
Linked Lists, but they give instantaneous access to elements like arrays.
So lets say we had a small java class that utilized Vectors. We want to add
words when a person says them into the Vector - as long as the word is not in
the Vector already. When they are done speaking, we want to print out all of
the words that they said.
import java.util.Vector;
public class SaveWords
{
public SaveWords(){
Vector v = new Vector();
String word = "";
while((word = WordISay()) != null) // as long as I say a word
{
if(!(v.contains(word))) // check to see if in Vector
{
// if not add it
v.add(word)
}
} // end while
// loop through the vector (notice the size() method)
for(int i = 0; i<v.size(); i++)
{
// use v.elementAt to get a specific element without
// removing it.
System.out.println(v.elementAt(i));
}
}
}
This is a simple walkthrough. Other useful and important methods deal with
removing an object and getting the index of an object. Look in the API for
these methods. Check out the elements method as well. This method returns
an Enumeration of all the elements in the Vector (see below).
ENUMERATION
============================================================================
The important methods for Enumeration are
hasMoreElements and nextElement.
hasMoreElements returns true if there are more elements while nextElement will
return the next Object of the Enumeration. Example of use...
Enumeration e.....
while(e.hasMoreElements()){
// do something with e.nextElement()
// remember that this is an Object and may need to be casted into the
// appropriate Object
} // end while
STRING TOKENIZER
=============================================================================
The StringTokenizer class is very similar to the Enumeration class with respect
to the methods that are able to be called. The small difference is that the
actual methods are called hasMoreTokens() and nextToken(). The nextToken method
returns a String as opposed to an Object. The StringTokenizer class does
exactly what it says...it tokenizes (breaks up) a string. The default delimiter
is white space. Thus if a StringTokenizer was declared as
StringTokenizer st = new StringTokenizer("How Are you doing?");
then the code
while(st.hasMoreTokens()){
System.out.println(st.nextToken());
}
would produce the following output
How
Are
you
doing?
if instead the StringTokenizer was declared to delimit with respect to o's
StringTokenizer st = new StringTokenizer("How Are you doing?", "o");
then the output would be...
H
w Are y
u d
ing?

BIN
CS1322/p3/cs1322-P3.zip Normal file

Binary file not shown.

524
CS1322/p3/p3.nfo.txt Normal file
View File

@@ -0,0 +1,524 @@
CS1322: Programming Assignment #3 - Fall 2002.
Assigned:
Phase 2 CheckOff: Monday, October 7th, 2002 at 23:59:59
Phase 4 Checkoff: Wednesday, October 16th, 2002 at 23:59:59
DUE Date: Wednesday, October 16th, 2002 at 23:59:59
Program Title: Telegram for Bugs
Files Provided
====================================================================
o p3.nfo.txt - this file
o P3Type.java - Interface needed for P3
o IOHelp.txt
o TricksandTools.txt
Learning Objectives
====================================================================
o File I/O
o Useful Java Tools
o Hashtables.
HASHTABLE OVERVIEW
====================================================================
A HashTable is a data structure which allows for the retrieval of
the information associated with a specified key value. They are made from
HashNodes. Thus you will add data to a HashNode and then add the HashNode
to the HashTable. A HashTable
first applies a hashing function to the key value to limit its range
to a reasonably small number. That hash value is then used to index
into an array to find the appropriate data. Since the hash function
is not one-to-one, it is possible that multiple key values could
hash to the same value- if this is the case, then a "collision"
occurs, and it must be resolved. Hashtables are useful for finding the
data quickly- the hashing operation occurs in O(1) time, and then,
as long as the number of collisions is small, the data may be found
with just a few operations- making for a very fast search. It should
be noted and emphasized that HashTables are based on an array.
A HashTable holds an array- what exactly that array holds depends
on the collision resoulution strategy used in the HashTable.
The size of the array is important- if the array is too small,
there will be many collisions, and operations will not be efficient.
If the array is too large, then there will be wasted space.
What is collision resolution?
Collision resolution is the process by which entires in a hashtable
that have the same hash value are handled. Typical methods include:
External chaining: The HashTable is an array of linked lists.
When a value is added to the table, it is hashed, then added
to the appropriate linked list. When a key is searched for,
it is hashed, then the correct linked list is searched for that
key and the associated data.
Open Addressing: When a value is added to the HashTable and the
desired space is full, an algorithm is applied to continue searching
through the array to find an empty space to put the element in.
There are two common forms:
- linear probing: the array index which is being attempted
is increased by a fixed ammount (i.e +1 each time) until
an open space is found.
- quadratic probing: the array index which is being attempted
is increased by an increasing ammount (i.e +1, then +2, then +3)
until an open space is found.
When searching for the data, the same probing function is applied
until the data is found.
Coalesced Chaining: An extra area (cellar) is allocated at the end of
the array (beyond the range of the hashing function), and when a
collision occurs, the data is stored in the first open space in the
cellar. When searching for the data, if it is not in the initial space,
the cellar is searched.
Multiple Record Buckets: Have room for a fixed number of collisions
to occur at each hash value (i.e. the HashTable is a 2D array).
When searching for the data, look in each of the spaces at that
hash value.
PROGRAM OVERVIEW
====================================================================
You will be making a simple telegram/postoffice for this assigment.
In order to accomplish this, you will make use of the data structre -
HashTable. You will use external chaining as the collision resolution
algorithm.
PROGRAM WALKTHROUGH
====================================================================
PHASE I - RECORD CLASSES (Mail.java and MailBox.java)
This phase should contain no more than 1 hour worth of coding. If you are
spending significantly more time than this then please come see a TA. All
the TA's are more than happy to help.
====================================================================
Mail.java
Since a post office handles mail, it will be useful to make a class for
mail. Make a Mail class that implements P3Type. This class should have
instance variables to store such things as who the mail is from,
who the mail is to, and what the message is.
Thus, there should be three private variables, all of which are Strings.
Call these variables:
strFrom;
strTo;
strMessage
Make accessors and modifiers for of these variables.
Next, you need to make a constructor which takes in the message, who
the message is from, and who the message is to. The constructor should
set each variable appropriately.
public Mail(String message, String from, String to)
Lastly, make override the toString method that will return a string
which looks like...
To: Honey Bee <enter>
From: Lovely Flower <enter>
Message: I don't like you stealing my sweets!
*********************************************************************
MailBox.java
Make a MailBox class that also implements P3Type and make it hold the first
and last name of the person who "owns" this mailbox. The mailbox will also
contain all the mail that the person has received.
Create three private instance variables:
String strLName;
String strFName;
Vector vMail;
For information on how to use Vectors and to find important methods in
the Vector class, consult TricksandTools.txt
Make sure you create accessors and modifiers for the person's last name
and first name.
Now create a constructor which will take in a person's last and first
name. You should set these two variables appropriately and initialize
the Vector.
public MailBox(String last, String first)
After completing that, you need to create a method for "placing" a piece
of mail into the persons mailbox. Call this method addMail. It should
take in Mail and add that mail to the vector of mail.
Now you are going to want to write a method that will return all the mail
that a person has. After people take mail out of their mailbox, the mail
is no longer there. When this method is called, not only should it return
all mail that is in the mailbox, it should also contain no more mail
(unless a person sends mail to them after they check their mailbox).
This means the you should "reset" your mail Vector.
This method - called getMail - will return an Enumeration containing all
the Mail currently in the mailbox.
Look in the TricksandTools.txt file for information about Enumeration as
well as other useful tools in Java.
Create a toString method which will return a String which contains the
name of the person who the mailbox is issued to as well as the number of
pieces of mail the person has in their mailbox.
an example of a String returned is...
FName LName has X piece(s) of mail.
so,
Really Popular has 1 piece of mail.
but,
Not Me has 4 pieces of mail.
Lastly, create an equals method that will compare two mailboxes to see if
they are equal. Two mailboxes are equal if they are "issued" to the same
person (meaning the last name and first name of the two mailboxes are
the same)
END OF PHASE 1!!!
====================================================================
PHASE 2. WORKING WITH FILE I/O (FileChanger.java)
INSTANT FEEDBACK PHASE
This phase should contain no more than 2 hours worth of coding. If you are
spending significantly more time than this then please come see a TA. All
the TA's are more than happy to help.
====================================================================
FileChanger.java
This file will allow you to read input from a file and write information
to a file.
If you read IOhelp.txt, this phase will be alot easier.
Create the appropriate variables needed for file io.
Also, create a private instance variable for the name of the file (strFileName)
The constructor for this class should take in a String - the fileName
The file name should be set appropriately.
Next create a method that will initialize all the buffers needed to read
the Objects from the file. This method will return true if the file is found.
It will return false if the file does not exist
public boolean initReader(){
}
Create a method that will initialize all the variables needed to write to
the file
public void initWriter(){
}
Now create a method that will return the next Object from the file.
If it encounters the end of the file, then null should be returned.
public Object nextObject(){
}
Next you need to write a method that will write an Object to the file.
public void writeObject(Object toWrite){
}
Write a method that will close all the buffers open to read the file
public void closeRead(){
}
Write a method that will close all the buffers open to write to the file
public void closeWrite(){
}
Write a main to test this class. Use your record classes written above to test
this class. One way of doing this would be to create a bunch of Mail and save
it to a file. Then read that file and print out all the Mail that is in there.
END OF PHASE 2!!!
Submit this phase to webwork for an autograded checkoff.
File(s) to submit: FileChanger.java
====================================================================
PHASE 3. HASHNODE IMPLEMENTATION (HashNode.java)
This phase should contain no more than 30 minutes of coding. If you are
spending significantly more time than this then please come see a TA. All
the TA's are more than happy to help.
====================================================================
A HashNode should contain Three private instance variables.
One is a reference to another HashNode. The other two are Objects -
one object is the key, and the other is the data.
HashNode next;
Object key;
Object data;
The constructor for this class should take in the key and the data;
public HashNode(Object key, Object data);
Make an equals method which will check to see if two HashNodes are equal
Two HashNodes are equal if they have the same key.
END OF PHASE 3!!!
====================================================================
PHASE 4. IMPLEMENTING a HASHTABLE (HashTable.java)
This phase should contain no more than 3 hours worth of coding. If you are
spending significantly more time than this then please come see a TA. All
the TA's are more than happy to help.
====================================================================
For this assignment you will be using external chaining as the
hashtable's collision avoidance. Call the hashtable hTable
The constructor should take in an int that will be the size of the array. The
constructor will initialize the array to the given size.
You will need to code the following methods
add(Object key, Object data)
get(Object key)
remove(Object key)
elements()
rehash(int iSize)
size()
toString()
The add method will add the data at the appropriate location. The location
to add the data is found by using the key passed in. Look up hashCode() in the
Object class.
**NOTE that the value returned from hashCode may be negative
The get method will return the data that is associated with the given key.
It will return null if the data is not found.
The remove method will remove a HashNode from the Hashtable. The Node that
will be removed will be the Node that contains the key. Make sure to return
the data that is held in the HashNode deleted (the data not the key).
If no HashNode is in the HashTable with the key, null is returned.
Elements should return an enumeration of all the data in the HashTable...they
should be HashNodes
The rehash method should resize the HashTable to the given size and readd
all the data to the appropriate location of the HashTable
size will return the size of the hashtable
toString will return a String representign all of the elements in the hashtable
Make sure to write a main to test this class
END OF PHASE 4!!!
Submit this phase to webwork for an autograded checkoff.
File(s) to submit: HashTable.java
====================================================================
PHASE 5. MAKING the POSTOFFICE (Manager.java, PostOffice.java)
This phase should contain no more than 5 hours worth of coding. If you are
spending significantly more time than this then please come see a TA. All
the TA's are more than happy to help.
====================================================================
Manager.java
This class will represent the person running the post office. All this person
is in charge of is performing operations given to him. The only functionality
of the assistant at this point will be:
Help Customer
Add More Rooms
View All MailBoxes
and Leave for the Day
When a customer comes into the post office, then the manager will be able to
Issue New Mailbox
Remove a Mailbox
Send a Telegram
and Retreive All Telegrams
Now that we know the basic operations of th manager, let's make the PostOffice
class so that the Manager can manage HIS PostOffice. We will come back to code
this class after we do the post office class
*********************************************************************
PostOffice.java
Make the PostOffice class implement P3Type. This class should contain only
one instance variable - A HashTable called htExpress. The default size should
be set to the default size in P3Type - 10.
The first method that you want to write is one which allows the post office to
issue another MailBox. Call this method issue. It wil take in the new Mailbox
and should add this mailbox to the Hashtable. REMEMBER, the key is the persons
last name. A person should not be allowed to have two mailboxes.
public void issue(MailBox mbToAdd)
The second method you will need to write is one that will retrieve all the mail
located in a person's mailbox. The person's last name will be passed in to
this method. If the person does not own a mailbox at this post office,
then return P3Type.NO_MAILBOX. Otherwise the method should
return a String representing all the mail that the person has received.
public String retrieve(String strLName)
Now write a method called send(Mail toSend). This method will return an int.
If the person trying to send the mail has never been issued a MailBox then
return P3Type.BAD_SENDER. This has first priority. If the recipient of the
mail has never been issued a MailBox before, then return P3Type.NO_RECIPIENT.
Otherwise add the mail to the recipients MailBox and return P3Type.MAIL_SENT.
In order to write this method, you will need to get the last name of the
sender and recipient. You can assume the last name of the person is all
of the characters after the last space. It may be beneficial to use
StringTokenizer.
public int send(Mail toSend)
Next write a method that removes a MailBox from the PostOffice. This method
should be called remove. It will return the number of unread telegrams in a
person's mailbox when it was deleted. If that MailBox has never been
issued, then return P3Type.NO_MAILBOX_NUM
public int remove(String strLName)
Another method that will be needed is one to retrieve all of the mailboxes in
the Post Office. This can be done by writing a wrapper method for the
HashTable elements(). All that needs to be done here is to return the
Enumeration of the HashTable.
public Enumeration allBoxes()
Lastly write a method that will resize the HashTable (This will make it
quicker for the assistant to find the correct mailbox). This method will
double the current size of the hashtable.
public void resize()
Remember to test this class
*********************************************************************
Now that we have coded the Post Office class, let's go back to the Manager.
The manager class needs to implement P3Type and hold 3 private instance
variables...a String for the customer's last and first name
(strCustLName and strCustFName), and a PostOffice
Make a method called managerActions() that returns a boolean
The boolean will be true if the manager has actions to perform and will be
false when the manager is ready to go home.
Have this method print out P3Type.INIT_ACTIONS. Then wait for the user
to make a choice. To figure out how to wait for user input from the keyboard
read the file IOhelp.txt.
The initial actions menu should look like this...
1) Help Customer
2) Add More Rooms
3) View All MailBoxes
0) Leave for the Day
If the user enters the selction 1, then you should prompt for the customer's
name and go to another method called customerHere() you should continue looping
to this method until it returns false (meaning the customer left)
If instead the selection choice were 2, then the manager would resize his
post office.
If 3 were selected, all of the mailboxes in the post office would be printed.
If the selection 0 were chosen, then false will be returned and the program
will exit.
The method customerHere() will take in a String strName and return a boolean.
The return will be true if the customer still wants to do something at the
postoffice. If the customer is done, then false will be returned.
First, you should print out the menu P3Type.CUST_HERE which looks like this:
1) I want a mailbox at this post office.
2) I no longer want a post office at this mailbox.
3) I want to send a telegram.
4) I want to read all of the telegrams I have received.
0) Okay, I am done.
If the customer chooses 1 then you will make a new mailbox and add it
to your post office.
If the customer chooses 2, you will try to remove the persons mailbox and then
do one of two things:
- Print P3Type.NO_MAILBOX if the person does not have a mailbox
- Or print P3Type.NUM_TELEGRAMS + the number of telgrams the person had
If the customer chooses 3, then you should prompt for the person who they
want to send the message to, and then prompt for the actual message. Next send
the message. And print out an appropriate message depending on the return
value
Lastly, if the customer chooses the 4 option, then retrieve all the telegrams
in his mailbox and print them to the standard out.
If 0 is selected, then you should return false and the managerActions menu will
be displayed.
Be SURE to test this class and make sure everything is working up to this point
(Since this is a small town, no two people have the same last name)
END OF PHASE 5!!!
====================================================================
PHASE 6. SAVING THE POSTOFFICE (Updates in Manager.java and PostOffice.java)
This phase should contain no more than 1 hour worth of coding. If you are
spending significantly more time than this then please come see a TA. All
the TA's are more than happy to help.
====================================================================
Inside of PostOffice.java, add one method. This method will be called
leavingForTheDay(). This method will be called when the manager chooses the
option 0 (Leave for the Day). In this method, you will save all of the
MailBoxes in the PostOffice to P3Type.POST_OFFICE.
*********************************************************************
Inside of Manager.java, you will have to do two things. First, make it call
leavingForTheDay when the manager decides to leave for the day (option 0)
Next, you will need to read from the file P3Type.POST_OFFICE and add all of the
mailboxes into the PostOffice. You can do this by calling issue(Mailbox)
*********************************************************************
Lastly, create a file called P3.java which will serve as the driver for this
project. This class should make an instance of manager and keep calling
managerActions() until the method returns false in which case it prints
P3Type.GOOD_BYE
END OF PHASE 6!!!
====================================================================
COMPILERS:
========================================================================
As a reminder, make sure that your program compiles and runs as expected
under Sun's JDK 1.3.1. Read the PROGRAM RESTRICTIONS section to see
what you can and cannot use to implement this program.
COMMENTS
========================================================================
You must comment your code thoroughly.
Each method should have a proper javadoc comment with the param and
return tags where needed. Each instance and static variable should be
javadocced. Any code that is not obvious should be explained briefly in
a comment. All closing braces should be commented.
TURNIN
========================================================================
Files to be turned in via Webwork:
(all .java files you made for this program)
This includes but is not limited to
- Mail.java
- MailBox.java
- FileChanger.java
- HashNode.java
- HashTable.java
- Manager.java
- PostOffice.java and
- P3.java

BIN
CS1322/p3/p3.zip Normal file

Binary file not shown.

BIN
CS1322/p3/toons.txt Normal file

Binary file not shown.