CSC212: Computer Science.
TEXTBOOK: Object-Oriented Data Structures Using Java
TEXTBOOK: Source Code
|
public class Circle implements Comparable
{
protected float radius;
protected static final float PI = 3.14f;
public Circle(float radius)
{
this.radius = radius;
}
public boolean equals(Circle circle)
// Precondition: circle != null
//
// Returns true if the circles have the same radius;
// otherwise, returns false.
{
if (this.radius == circle.radius)
return true;
else
return false;
}
public int compareTo(Circle o)
// Precondition: o != null
//
// Returns a negative integer, zero, or a positive integer as this Circle
// is less than, equal to, or greater than the parameter Circle.
{
if (this.radius < o.radius)
return -1;
else
if (this.radius == o.radius)
return 0;
else
return 1;
}
public float perimeter()
// Returns perimeter of this figure.
{
return(2 * PI * radius);
}
public float area()
// Returns area of this figure.
{
return(PI * radius * radius);
}
}
|
|
public interface FigureGeometry
{
final float PI = 3.14f;
float perimeter();
// Returns perimeter of this figure.
float area();
// Returns area of this figure.
void setScale(int scale);
// Scale of this figure is set to "scale".
float weight();
// Precondition: Scale of this figure has been set.
//
// Returns weight of this figure. Weight = area X scale.
}
|
|
//---------------------------------------------------------------------
// GolfApp.java by Dale/Joyce/Weems Chapter 6
//
// Allows user to enter golfer name and score information.
// Displays information ordered by score.
//----------------------------------------------------------------------
import java.util.Scanner;
import ch06.lists.*;
import support.*; // Golfer
public class GolfApp
{
public static void main(String[] args)
{
Scanner conIn = new Scanner(System.in);
String name; // golfer's name
int score; // golfer's score
ListInterface golfers = new ArraySortedList(20);
Golfer golfer;
String skip; // Used to skip rest of input line after reading integer
System.out.print("Golfer name (press Enter to end): ");
name = conIn.nextLine();
while (!name.equals(""))
{
System.out.print("Score: ");
score = conIn.nextInt();
skip = conIn.nextLine();
golfer = new Golfer(name, score);
golfers.add(golfer);
System.out.print("Golfer name (press Enter to end): ");
name = conIn.nextLine();
}
System.out.println();
System.out.println("The final results are");
System.out.println(golfers);
}
}
|
|
//-------------------------------------------------------------------------
// ArrayIndexedList.java by Dale/Joyce/Weems Chapter 6
//
// Implements the IndexedListInterface using an array.
//
// Null elements are not permitted on a list.
//
// Two constructors are provided: one that creates a list of a default
// original capacity, and one that allows the calling program to specify the
// original capacity.
//----------------------------------------------------------------------------
package ch06.lists;
public class ArrayIndexedList extends ArrayUnsortedList
implements IndexedListInterface
{
public ArrayIndexedList()
{
super();
}
public ArrayIndexedList(int origCap)
{
super(origCap);
}
public void add(int index, T element)
// Throws IndexOutOfBoundsException if passed an index argument
// such that index < 0 or index > size().
// Otherwise, adds element to this list at position index; all current
// elements at that index or higher have 1 added to their index.
{
if ((index < 0) || (index > size()))
throw new IndexOutOfBoundsException("illegal index of " + index +
" passed to ArrayIndexedList add method.\n");
if (numElements == list.length)
enlarge();
for (int i = numElements; i > index; i--)
list[i] = list[i - 1];
list[index] = element;
numElements++;
}
public T set(int index, T element)
// Throws IndexOutOfBoundsException if passed an index argument
// such that index < 0 or index >= size().
// Otherwise, replaces element on this list at position index and
// returns the replaced element.
{
if ((index < 0) || (index >= size()))
throw new IndexOutOfBoundsException("illegal index of " + index +
" passed to ArrayIndexedList set method.\n");
T hold = list[index];
list[index] = element;
return hold;
}
public T get(int index)
// Throws IndexOutOfBoundsException if passed an index argument
// such that index < 0 or index >= size().
// Otherwise, returns the element on this list at position index.
{
if ((index < 0) || (index >= size()))
throw new IndexOutOfBoundsException("illegal index of " + index +
" passed to ArrayIndexedList set method.\n");
return list[index];
}
public int indexOf(T element)
// If this list contains an element e such that e.equals(element),
// then returns the index of the first such element.
// Otherwise, returns -1.
{
find(element);
if (found)
return location;
else
return -1;
}
public T remove(int index)
// Throws IndexOutOfBoundsException if passed an index argument
// such that index < 0 or index >= size().
// Otherwise, removes element on this list at position index and
// returns the removed element; all current elements at positions
// higher than that index have 1 subtracted from their index.
{
if ((index < 0) || (index >= size()))
throw new IndexOutOfBoundsException("illegal index of " + index +
" passed to ArrayIndexedList remove method.\n");
T hold = list[index];
for (int i = index; i < numElements; i++)
list[i] = list[i + 1];
list[numElements] = null;
numElements--;
return hold;
}
public String toString()
// Returns a nicely formatted string that represents this list.
{
String listString = "List:\n";
for (int i = 0; i < numElements; i++)
listString = listString + "[" + i + "] " + list[i] + "\n";
return listString;
}
}
|
|
//----------------------------------------------------------------------------
// ArraySortedList.java by Dale/Joyce/Weems Chapter 6
//
// Implements the ListInterface using an array. It is kept in increasing order
// as defined by the compareTo method of the added elements. Only Comparable
// elements may be added to a list.
//
// Null elements are not permitted on a list.
//
// Two constructors are provided: one that creates a list of a default
// original capacity, and one that allows the calling program to specify the
// original capacity.
//----------------------------------------------------------------------------
package ch06.lists;
public class ArraySortedList extends ArrayUnsortedList
implements ListInterface
{
public ArraySortedList()
{
super();
}
public ArraySortedList(int origCap)
{
super(origCap);
}
public void add(T element)
// Precondition: element is Comparable.
//
// Adds element to this list.
{
T listElement;
int location = 0;
if (numElements == list.length)
enlarge();
while (location < numElements)
{
listElement = (T)list[location];
if (((Comparable)listElement).compareTo(element) < 0) // list element < add element
location++;
else
break; // list element >= add element
}
for (int index = numElements; index > location; index--)
list[index] = list[index - 1];
list[location] = element;
numElements++;
}
public boolean remove (T element)
// Removes an element e from this list such that e.equals(element)
// and returns true; if no such element exists, returns false.
{
find(element);
if (found)
{
for (int i = location; i <= numElements - 2; i++)
list[i] = list[i+1];
list[numElements - 1] = null;
numElements--;
}
return found;
}
}
|
|
//----------------------------------------------------------------------------
// ArraySortedList2.java by Dale/Joyce/Weems Chapter 6
//
// Implements the ListInterface using an array. It is kept in increasing order
// as defined by the compareTo method of the added elements. Only Comparable
// elements may be added to a list.
//
// Null elements are not permitted on a list.
//
// Two constructors are provided: one that creates a list of a default
// original capacity, and one that allows the calling program to specify the
// original capacity.
//----------------------------------------------------------------------------
package ch06.lists;
public class ArraySortedList2 extends ArrayUnsortedList
implements ListInterface
{
public ArraySortedList2()
{
super();
}
public ArraySortedList2(int origCap)
{
super(origCap);
}
protected void find(T target)
// Searches list for an occurrence of an element e such that
// target.equals(e). If successful, sets instance variables
// found to true and location to the array index of e. If
// not successful, sets found to false.
{
int first = 0;
int last = numElements - 1;
int compareResult;
Comparable targetElement = (Comparable) target;
found = false;
while (first <= last)
{
location = (first + last) / 2;
compareResult = targetElement.compareTo(list[location]);
if (compareResult == 0)
{
found = true;
break;
}
else if (compareResult < 0)
// target element is less than element at location
last = location - 1;
else // target element is greater than element at location
first = location + 1;
}
}
public void add(T element)
// Precondition: element is Comparable.
//
// Adds element to this list.
{
T listElement;
int location = 0;
if (numElements == list.length)
enlarge();
while (location < numElements)
{
listElement = (T)list[location];
if (((Comparable)listElement).compareTo(element) < 0) // list element < add element
location++;
else
break; // list element >= add element
}
for (int index = numElements; index > location; index--)
list[index] = list[index - 1];
list[location] = element;
numElements++;
}
public boolean remove (T element)
// Removes an element e from this list such that e.equals(element)
// and returns true; if no such element exists, returns false.
{
find(element);
if (found)
{
for (int i = location; i <= numElements - 2; i++)
list[i] = list[i+1];
list[numElements - 1] = null;
numElements--;
}
return found;
}
}
|
|
//----------------------------------------------------------------------------
// ArraySortedList3.java by Dale/Joyce/Weems Chapter 6
//
// Implements the ListInterface using an array. It is kept in increasing order
// as defined by the compareTo method of the added elements. Only Comparable
// elements may be added to a list.
//
// Null elements are not permitted on a list.
//
// Two constructors are provided: one that creates a list of a default
// original capacity, and one that allows the calling program to specify the
// original capacity.
//----------------------------------------------------------------------------
package ch06.lists;
public class ArraySortedList3 extends ArrayUnsortedList
implements ListInterface
{
public ArraySortedList3()
{
super();
}
public ArraySortedList3(int origCap)
{
super(origCap);
}
protected void recFind(Comparable target, int fromLocation, int toLocation)
// Searches list between fromLocation and toLocation
// for an occurrence of an element e such that
// target.equals(e). If successful, sets instance variables
// found to true and location to the array index of e. If
// not successful, sets found to false.
{
if (fromLocation > toLocation) // Base case 1
found = false;
else
{
int compareResult;
location = (fromLocation + toLocation) / 2;
compareResult = target.compareTo(list[location]);
if (compareResult == 0) // Base case 2
found = true;
else if (compareResult < 0)
// target is less than element at location
recFind (target, fromLocation, location - 1);
else
// target is greater than element at location
recFind (target, location + 1, toLocation);
}
}
protected void find(T target)
// Searches list for an occurrence of an element e such that
// target.equals(e). If successful, sets instance variables
// found to true and location to the array index of e. If
// not successful, sets found to false.
{
Comparable targetElement = (Comparable)target;
found = false;
recFind(targetElement, 0, numElements - 1);
}
public void add(T element)
// Precondition: element is Comparable.
//
// Adds element to this list.
{
T listElement;
int location = 0;
if (numElements == list.length)
enlarge();
while (location < numElements)
{
listElement = (T)list[location];
if (((Comparable)listElement).compareTo(element) < 0) // list element < add element
location++;
else
break; // list element >= add element
}
for (int index = numElements; index > location; index--)
list[index] = list[index - 1];
list[location] = element;
numElements++;
}
public boolean remove (T element)
// Removes an element e from this list such that e.equals(element)
// and returns true; if no such element exists, returns false.
{
find(element);
if (found)
{
for (int i = location; i <= numElements - 2; i++)
list[i] = list[i+1];
list[numElements - 1] = null;
numElements--;
}
return found;
}
}
|
|
//----------------------------------------------------------------------------
// ArrayUnsortedList.java by Dale/Joyce/Weems Chapter 6
//
// Implements the ListInterface using an array.
//
// Null elements are not permitted on a list.
//
// Two constructors are provided: one that creates a list of a default
// original capacity, and one that allows the calling program to specify the
// original capacity.
//----------------------------------------------------------------------------
package ch06.lists;
public class ArrayUnsortedList implements ListInterface
{
protected final int DEFCAP = 100; // default capacity
protected int origCap; // original capacity
protected T[] list; // array to hold this listís elements
protected int numElements = 0; // number of elements in this list
protected int currentPos; // current position for iteration
// set by find method
protected boolean found; // true if element found, otherwise false
protected int location; // indicates location of element if found
public ArrayUnsortedList()
{
list = (T[]) new Object[DEFCAP];
origCap = DEFCAP;
}
public ArrayUnsortedList(int origCap)
{
list = (T[]) new Object[origCap];
this.origCap = origCap;
}
protected void enlarge()
// Increments the capacity of the list by an amount
// equal to the original capacity.
{
// Create the larger array.
T[] larger = (T[]) new Object[list.length + origCap];
// Copy the contents from the smaller array into the larger array.
for (int i = 0; i < numElements; i++)
{
larger[i] = list[i];
}
// Reassign list reference.
list = larger;
}
protected void find(T target)
// Searches list for an occurence of an element e such that
// e.equals(target). If successful, sets instance variables
// found to true and location to the array index of e. If
// not successful, sets found to false.
{
location = 0;
found = false;
while (location < numElements)
{
if (list[location].equals(target))
{
found = true;
return;
}
else
location++;
}
}
public void add(T element)
// Adds element to this list.
{
if (numElements == list.length)
enlarge();
list[numElements] = element;
numElements++;
}
public boolean remove (T element)
// Removes an element e from this list such that e.equals(element)
// and returns true; if no such element exists, returns false.
{
find(element);
if (found)
{
list[location] = list[numElements - 1];
list[numElements - 1] = null;
numElements--;
}
return found;
}
public int size()
// Returns the number of elements on this list.
{
return numElements;
}
public boolean contains (T element)
// Returns true if this list contains an element e such that
// e.equals(element); otherwise, returns false.
{
find(element);
return found;
}
public T get(T element)
// Returns an element e from this list such that e.equals(element);
// if no such element exists, returns null.
{
find(element);
if (found)
return list[location];
else
return null;
}
public String toString()
// Returns a nicely formatted string that represents this list.
{
String listString = "List:\n";
for (int i = 0; i < numElements; i++)
listString = listString + " " + list[i] + "\n";
return listString;
}
public void reset()
// Initializes current position for an iteration through this list,
// to the first element on this list.
{
currentPos = 0;
}
public T getNext()
// Preconditions: The list is not empty
// The list has been reset
// The list has not been modified since the most recent reset
//
// Returns the element at the current position on this list.
// If the current position is the last element, it advances the value
// of the current position to the first element; otherwise, it advances
// the value of the current position to the next element.
{
T next = list[currentPos];
if (currentPos == (numElements - 1))
currentPos = 0;
else
currentPos++;
return next;
}
}
|
|
//----------------------------------------------------------------------
// IndexedListInterface.java by Dale/Joyce/Weems Chapter 6
//
// Extends the ListInterface with methods specific to indexed lists.
//----------------------------------------------------------------------
package ch06.lists;
public interface IndexedListInterface extends ListInterface
{
void add(int index, T element);
// Throws IndexOutOfBoundsException if passed an index argument
// such that index < 0 or index > size().
// Otherwise, adds element to this list at position index; all current
// elements at that position or higher have 1 added to their index.
T set(int index, T element);
// Throws IndexOutOfBoundsException if passed an index argument
// such that index < 0 or index >= size().
// Otherwise, replaces element on this list at position index and
// returns the replaced element.
T get(int index);
// Throws IndexOutOfBoundsException if passed an index argument
// such that index < 0 or index >= size().
// Otherwise, returns the element on this list at position index.
int indexOf(T element);
// If this list contains an element e such that e.equals(element),
// then returns the index of the first such element.
// Otherwise, returns -1.
T remove(int index);
// Throws IndexOutOfBoundsException if passed an index argument
// such that index < 0 or index >= size().
// Otherwise, removes element on this list at position index and
// returns the removed element; all current elements at positions
// higher than that position have 1 subtracted from their index.
}
|
|
//----------------------------------------------------------------------------
// ListInterface.java by Dale/Joyce/Weems Chapter 6
//
// The lists are unbounded and allow duplicate elements, but do not allow
// null elements. As a general precondition, null elements are not passed as
// arguments to any of the methods.
//
// The list has a special property called the current position - the position
// of the next element to be accessed by getNext during an iteration through
// the list. Only reset and getNext affect the current position.
//----------------------------------------------------------------------------
package ch06.lists;
public interface ListInterface
{
int size();
// Returns the number of elements on this list.
void add(T element);
// Adds element to this list.
boolean remove (T element);
// Removes an element e from this list such that e.equals(element)
// and returns true; if no such element exists, returns false.
boolean contains (T element);
// Returns true if this list contains an element e such that
// e.equals(element); otherwise, returns false.
T get(T element);
// Returns an element e from this list such that e.equals(element);
// if no such element exists, returns null.
String toString();
// Returns a nicely formatted string that represents this list.
void reset();
// Initializes current position for an iteration through this list,
// to the first element on this list.
T getNext();
// Preconditions: The list is not empty
// The list has been reset
// The list has not been modified since the most recent reset
//
// Returns the element at the current position on this list.
// If the current position is the last element, then it advances the value
// of the current position to the first element; otherwise, it advances
// the value of the current position to the next element.
}
|
|
//-------------------------------------------------------------------------
// RefSortedList.java by Dale/Joyce/Weems Chapter 6
//
// Implements the ListInterface using a linked list. It is kept in increasing
// order as defined by the compareTo method of the added elements. Only
// Comparable elements may be added to a list.
//
// Null elements are not permitted on a list.
//
// One constructor is provided, one that creates an empty list.
//----------------------------------------------------------------------------
package ch06.lists;
import support.LLNode;
public class RefSortedList>
extends RefUnsortedList
implements ListInterface
{
public RefSortedList()
{
super();
}
public void add(T element)
// Adds element to this list.
{
LLNode prevLoc; // trailing reference
LLNode location; // traveling reference
T listElement; // current list element being compared
// Set up search for insertion point.
location = list;
prevLoc = null;
// Find insertion point.
while (location != null)
{
listElement = location.getInfo();
if (listElement.compareTo(element) < 0) // list element < add element
{
prevLoc = location;
location = location.getLink();
}
else
break;
}
// Prepare node for insertion.
LLNode newNode = new LLNode(element);
// Insert node into list.
if (prevLoc == null)
{
// Insert as first node.
newNode.setLink(list);
list = newNode;
}
else
{
// Insert elsewhere.
newNode.setLink(location);
prevLoc.setLink(newNode);
}
numElements++;
}
}
|
|
//----------------------------------------------------------------------------
// RefUnsortedList.java by Dale/Joyce/Weems Chapter 6
//
// Implements the ListInterface using references (a linked list).
//
// Null elements are not permitted on a list.
//
// One constructor is provided, one that creates an empty list.
//----------------------------------------------------------------------------
package ch06.lists;
import support.LLNode;
public class RefUnsortedList implements ListInterface
{
protected int numElements; // number of elements in this list
protected LLNode currentPos; // current position for iteration
// set by find method
protected boolean found; // true if element found, else false
protected LLNode location; // node containing element, if found
protected LLNode previous; // node preceeding location
protected LLNode list; // first node on the list
public RefUnsortedList()
{
numElements = 0;
list = null;
currentPos = null;
}
public void add(T element)
// Adds element to this list.
{
LLNode newNode = new LLNode(element);
newNode.setLink(list);
list = newNode;
numElements++;
}
protected void find(T target)
// Searches list for an occurence of an element e such that
// e.equals(target). If successful, sets instance variables
// found to true, location to node containing e, and previous
// to the node that links to location. If not successful, sets
// found to false.
{
location = list;
found = false;
while (location != null)
{
if (location.getInfo().equals(target)) // if they match
{
found = true;
return;
}
else
{
previous = location;
location = location.getLink();
}
}
}
public int size()
// Returns the number of elements on this list.
{
return numElements;
}
public boolean contains (T element)
// Returns true if this list contains an element e such that
// e.equals(element); otherwise, returns false.
{
find(element);
return found;
}
public boolean remove (T element)
// Removes an element e from this list such that e.equals(element)
// and returns true; if no such element exists, returns false.
{
find(element);
if (found)
{
if (list == location)
list = list.getLink(); // remove first node
else
previous.setLink(location.getLink()); // remove node at location
numElements--;
}
return found;
}
public T get(T element)
// Returns an element e from this list such that e.equals(element);
// if no such element exists, returns null.
{
find(element);
if (found)
return location.getInfo();
else
return null;
}
public String toString()
// Returns a nicely formatted string that represents this list.
{
LLNode currNode = list;
String listString = "List:\n";
while (currNode != null)
{
listString = listString + " " + currNode.getInfo() + "\n";
currNode = currNode.getLink();
}
return listString;
}
public void reset()
// Initializes current position for an iteration through this list,
// to the first element on this list.
{
currentPos = list;
}
public T getNext()
// Preconditions: The list is not empty
// The list has been reset
// The list has not been modified since most recent reset
//
// Returns the element at the current position on this list.
// If the current position is the last element, then it advances the value
// of the current position to the first element; otherwise, it advances
// the value of the current position to the next element.
{
T next = currentPos.getInfo();
if (currentPos.getLink() == null)
currentPos = list;
else
currentPos = currentPos.getLink();
return next;
}
}
|
|
//---------------------------------------------------------------------
// PokerApp.java by Dale/Joyce/Weems Chapter 6
//
// Simulates dealing poker hands to calculate the probability of
// getting at least one pair of matching cards.
//----------------------------------------------------------------------
import ch06.lists.*;
import support.*; // RankCardDeck
public class PokerApp
{
public static void main(String[] args)
{
final int HANDSIZE = 7; // number of cards per hand
final int NUMHANDS = 1000000; // total number of hands
int numPairs = 0; // number of hands with pairs
boolean isPair; // status of current hand
float probability; // calculated probability
ListInterface hand;
RankCardDeck deck = new RankCardDeck();
int card;
for (int i = 0; i < NUMHANDS; i++)
{
deck.shuffle();
hand = new ArrayUnsortedList(HANDSIZE);
isPair = false;
for (int j = 0; j < HANDSIZE; j++)
{
card = deck.nextCard();
if (hand.contains(card))
isPair = true;
hand.add(card);
}
if (isPair)
numPairs = numPairs + 1;
}
probability = numPairs/(float)NUMHANDS;
System.out.println();
System.out.print("There were " + numPairs + " hands out of " + NUMHANDS);
System.out.println(" that had at least one pair of matched cards.");
System.out.print("The probability of getting at least one pair,");
System.out.print(" based on this simulation, is ");
System.out.println(probability);
}
}
|
|
[ViewState]
Mode=
Vid=
FolderType=NotSpecified
|
|
//-------------------------------------------------------------------------
// SArrayIndexedList.java by Dale/Joyce/Weems Chapter 6
//
// Implements the SIndexedListInterface using an array.
//-------------------------------------------------------------------------
package ch06.serLists;
import java.lang.*;
import java.io.*;
public class SArrayIndexedList extends SList implements SIndexedListInterface,
Serializable
{
public SArrayIndexedList()
{
super();
}
public SArrayIndexedList(int origCap)
{
super(origCap);
}
public void add(int index, Serializable element)
// Throws IndexOutOfBoundsException if passed an index argument
// such that index < 0 or index > size().
// Otherwise, adds element to this list at position index; all current
// elements at that index or higher have 1 added to their index.
{
if ((index < 0) || (index > size()))
throw new IndexOutOfBoundsException("illegal index of " + index +
" passed to ArrayIndexedList add method.\n");
if (numElements == list.length)
enlarge();
for (int i = numElements; i > index; i--)
list[i] = list[i - 1];
list[index] = element;
numElements = numElements + 1;
}
public Object set(int index, Serializable element)
// Throws IndexOutOfBoundsException if passed an index argument
// such that index < 0 or index >= size().
// Otherwise, replaces element on this list at position index and
// returns the replaced element.
{
if ((index < 0) || (index >= size()))
throw new IndexOutOfBoundsException("illegal index of " + index +
" passed to ArrayIndexedList set method.\n");
Object hold = list[index];
list[index] = element;
return hold;
}
public Object get(int index)
// Throws IndexOutOfBoundsException if passed an index argument
// such that index < 0 or index >= size().
// Otherwise, returns the element on this list at position index.
{
if ((index < 0) || (index >= size()))
throw new IndexOutOfBoundsException("illegal index of " + index +
" passed to ArrayIndexedList set method.\n");
return list[index];
}
public int indexOf(Object element)
// If this list contains an element e such that e.equals(element),
// then it returns the index of the first such element.
// Otherwise, returns -1.
{
find(element);
if (found)
return location;
else
return -1;
}
public Object remove(int index)
// Throws IndexOutOfBoundsException if passed an index argument
// such that index < 0 or index >= size().
// Otherwise, removes element on this list at position index and
// returns the removed element; all current elements at positions
// higher than that index have 1 subtracted from their index.
{
if ((index < 0) || (index >= size()))
throw new IndexOutOfBoundsException("illegal index of " + index +
" passed to ArrayIndexedList remove method.\n");
Object hold = list[index];
for (int i = index; i < numElements; i++)
list[index] = list[index + 1];
list[numElements] = null;
return hold;
}
public String toString()
// Returns a nicely formatted string that represents this list.
{
String listString = "List:\n";
for (int i = 0; i < numElements; i++)
listString = listString + "[" + i + "] " + list[i] + "\n";
return listString;
}
}
|
|
//----------------------------------------------------------------------
// SerSongList.java by Dale/Joyce/Weems Chapter 6
//
// Supports a list of song objects having a name and a total duration.
// Allows application to view indexing as starting at 1.
// Implements Serializable.
//----------------------------------------------------------------------
package ch06.serLists;
import java.io.*; // Serializable interface
import java.text.*; // DecimalFormat
import support.*; // SerSong
public class SerSongList implements Serializable
{
protected String listName; // name of song list
protected int totDuration = 0; // total duration of songs in seconds
protected SArrayIndexedList songList;
DecimalFormat fmt = new DecimalFormat("00"); // to format seconds
public SerSongList(String listName)
{
this.listName = listName;
songList = new SArrayIndexedList(10);
}
public String getListName()
{
return listName;
}
public int getTotDuration()
{
return totDuration;
}
public int getSize()
{
return songList.size();
}
public void add(int number, SerSong song)
// If number is a legal position, then adds song onto the
// indexed songList at position (number - 1).
// Otherwise, adds song at the end of the songList.
{
totDuration = totDuration + song.getDuration();
if ((number <= 0) || (number > (songList.size() + 1)))
songList.add(songList.size(), song);
else
songList.add(number - 1, song);
}
public String toString()
{
// Returns a nicely formatted string that represents this SerSongList.
SerSong song;
int duration;
int numSongs = songList.size();
String hold = listName + ":\n";
for (int i = 0; i < numSongs; i++)
{
song = (SerSong)songList.get(i);
duration = song.getDuration();
hold = hold + (i + 1) + ": " + song.getName() + " ["
+ (duration / 60) + ":" + fmt.format(duration % 60) + "]\n";
}
hold = hold + "\n";
hold = hold + "Total Time: " + (totDuration / 60) +" minutes, "
+ fmt.format(totDuration % 60) + " seconds\n";
return hold;
}
}
|
|
//----------------------------------------------------------------------
// SIndexedListInterface.java by Dale/Joyce/Weems Chapter 6
//
// Extends the SListInterface with methods specific to Indexed Lists.
//----------------------------------------------------------------------
package ch06.serLists;
import java.io.*;
public interface SIndexedListInterface extends SListInterface
{
void add(int index, Serializable element);
// Throws IndexOutOfBoundsException if passed an index argument
// such that index < 0 or index > size().
// Otherwise, adds element to this list at position index; all current
// elements at that position or higher have 1 added to their index.
Object set(int index, Serializable element);
// Throws IndexOutOfBoundsException if passed an index argument
// such that index < 0 or index >= size().
// Otherwise, replaces element on this list at position index and
// returns the replaced element.
Object get(int index);
// Throws IndexOutOfBoundsException if passed an index argument
// such that index < 0 or index >= size().
// Otherwise, returns the element on this list at position index.
int indexOf(Object element);
// If this list contains an element e such that e.equals(element),
// then returns the index of the first such element.
// Otherwise, returns -1.
Object remove(int index);
// Throws IndexOutOfBoundsException if passed an index argument
// such that index < 0 or index >= size().
// Otherwise, removes element on this list at position index and
// returns the removed element; all current elements at positions
// higher than that position have 1 subtracted from their index.
}
|
|
//----------------------------------------------------------------------------
// SList.java by Dale/Joyce/Weems Chapter 6
//
// Defines constructs for an unbounded array-based list of objects that do
// not depend on whether the list is sorted or indexed.
//
// Our intention is for this class to be extended by other classes that furnish
// the remaining methods needed to support a list, for example a method that
// allows objects to be added to the list.
//
// Null elements are not permitted on a list.
// The list is Serializable.
//
// Two constructors are provided: one that creates a list of a default
// original capacity, and one that allows the calling program to specify the
// original capacity.
//---------------------------------------------------------------------------
package ch06.serLists;
import java.io.*;
public class SList implements Serializable
{
protected final int DEFCAP = 100; // default capacity
protected int origCap; // original capacity
protected Serializable[] list; // array to hold this listís elements
protected int numElements = 0; // number of elements in this list
protected int currentPos; // current position for iteration
// set by find method
protected boolean found; // true if element found, otherwise false
protected int location; // indicates location of element if found
public SList()
{
list = new Serializable[DEFCAP];
origCap = DEFCAP;
}
public SList(int origCap)
{
list = new Serializable[origCap];
this.origCap = origCap;
}
protected void enlarge()
// Increments the capacity of the list by an amount
// equal to the original capacity.
// Used by subclasses that provide an add method.
{
// create the larger array
Serializable[] larger = new Serializable[list.length + origCap];
// copy the contents from the smaller array into the larger array
for (int i = 0; i < numElements; i++)
{
larger[i] = list[i];
}
// reassign list reference
list = larger;
}
protected void find(Object target)
// Searches list for an occurence of an element e such that
// e.equals(target). If successful, sets instance variables
// found to true and location to the array index of e. If
// not successful, sets found to false.
{
boolean moreToSearch;
location = 0;
found = false;
moreToSearch = (location < numElements);
while (moreToSearch && !found)
{
if (list[location].equals(target))
found = true;
else
{
location++;
moreToSearch = (location < numElements);
}
}
}
public int size()
// Returns the number of elements on this list.
{
return numElements;
}
public boolean contains (Object element)
// Returns true if this list contains an element e such that
// e.equals(element), otherwise, returns false.
{
find(element);
return found;
}
public boolean remove (Object element)
// Removes an element e from this list such that e.equals(element)
// and returns true; if no such element exists, returns false.
{
find(element);
if (found)
{
for (int i = location; i <= numElements - 2; i++)
list[i] = list[i+1];
list[numElements - 1] = null;
numElements--;
}
return found;
}
public Object get(Object element)
// Returns an element e from this list such that e.equals(element);
// if no such element exists, returns null.
{
find(element);
if (found)
return list[location];
else
return null;
}
public String toString()
// Returns a nicely formatted string that represents this list.
{
String listString = "List:\n";
for (int i = 0; i < numElements; i++)
listString = listString + " " + list[i] + "\n";
return listString;
}
public void reset()
// Initializes current position for an iteration through this list,
// to the first element on this list.
{
currentPos = 0;
}
public Object getNext()
// Preconditions: The list is not empty
// The list has been reset
// The list has not been modified since the most recent reset
//
// Returns the element at the current position on this list.
// If the current position is the last element, then it advances the value
// of the current position to the first element; otherwise, it advances
// the value of the current position to the next element.
{
Object next = list[currentPos];
if (currentPos == (numElements - 1))
currentPos = 0;
else
currentPos++;
return next;
}
}
|
|
//----------------------------------------------------------------------------
// SListInterface.java by Dale/Joyce/Weems Chapter 6
//
// Interface that defines methods common to our various kinds of list.
// Our intention is that this interface will be extended by other interfaces
// directly related to the specific kind of list. Those interfaces, in turn,
// will be implemented by classes.
//
// The lists are unbounded, allow duplicate elements, but do not allow null
// elements. As a general precondition, null elements are not passed as
// arguments to any of the methods. The lists are serializable.
//
// The list has a special property called the current position - the position
// of the next element to be accessed by getNext during an iteration through
// the list. Only reset and getNext affect the current position.
//----------------------------------------------------------------------------
package ch06.serLists;
public interface SListInterface
{
int size();
// Returns the number of elements on this list.
boolean contains (Object element);
// Returns true if this list contains an element e such that
// e.equals(element); otherwise, returns false.
boolean remove (Object element);
// Removes an element e from this list such that e.equals(element)
// and returns true; if no such element exists, returns false.
Object get(Object element);
// Returns an element e from this list such that e.equals(element);
// if no such element exists, returns null.
String toString();
// Returns a nicely formatted string that represents this list.
void reset();
// Initializes current position for an iteration through this list,
// to the first element on this list.
Object getNext();
// Preconditions: The list is not empty
// The list has been reset
// The list has not been modified since the most recent reset
//
// Returns the element at the current position on this list.
// If the current position is the last element, then it advances the value
// of the current position to the first element; otherwise, it advances
// the value of the current position to the next element.
}
|
|
//---------------------------------------------------------------------
// SongsApp.java by Dale/Joyce/Weems Chapter 6
//
// Allows user to enter a collection of songs.
// Keeps track of order and total time.
//----------------------------------------------------------------------
import java.util.Scanner;
import java.text.*;
import ch06.lists.*;
import support.*; // for Song
public class SongsApp
{
public static void main(String[] args)
{
Scanner conIn = new Scanner(System.in);
String name; // song name
int minutes; // song duration
int seconds; // song duration
int number; // song number
int numSongs = 0; // number of songs entered
int totTime = 0; // total duration of songs entered so far
DecimalFormat fmt = new DecimalFormat("00"); // to format seconds
ArrayIndexedList songList = new ArrayIndexedList(20);
Song song;
String skip; // Used to skip rest of input line after reading integer
System.out.print("Song name (press Enter to end): ");
name = conIn.nextLine();
while (!name.equals(""))
{
System.out.print("Minutes: ");
minutes = conIn.nextInt();
skip = conIn.nextLine();
System.out.print("Seconds: ");
seconds = conIn.nextInt();
skip = conIn.nextLine();
totTime = totTime + (minutes * 60) + seconds;
song = new Song(name, minutes, seconds);
System.out.print("Song number between 0 and " + songList.size() + ": ");
number = conIn.nextInt();
skip = conIn.nextLine();
songList.add(number, song);
System.out.println();
System.out.println(songList);
System.out.println("Total Time: " + (totTime / 60) + ":"
+ fmt.format(totTime % 60));
System.out.println();
System.out.print("Song name (press Enter to end): ");
name = conIn.nextLine();
}
System.out.println();
System.out.println("The final result is \n");
System.out.println(songList);
System.out.println("Total Time: " + (totTime / 60) +":"
+ fmt.format(totTime % 60));
System.out.println();
}
}
|
|
import java.io.*;
import support.*;
public class GetSerSong
{
public static void main(String[] args) throws IOException
{
SerSong song2;
ObjectInputStream in = new ObjectInputStream(new
FileInputStream("song.dat"));
try
{
song2 = (SerSong)in.readObject();
System.out.println("The name of the song is " + song2.getName());
System.out.println("The duration of the song is " + song2.getDuration());
}
catch (Exception e)
{
System.out.println("Error in readObject: " + e);
System.exit(1);
}
}
}
|
|
import java.io.*;
import java.util.*;
import support.*;
public class GetSong
{
public static void main(String[] args) throws IOException
{
String name;
int duration;
FileReader fin = new FileReader("song.txt");
Scanner songIn = new Scanner(fin);
name = songIn.nextLine();
duration = songIn.nextInt();
Song song2 = new Song(name, duration);
System.out.println("The name of the song is " + song2.getName());
System.out.println("The duration of the song is " + song2.getDuration());
}
}
|
|
import java.io.*;
import support.*;
public class SaveSerSong
{
private static PrintWriter outFile;
public static void main(String[] args) throws IOException
{
SerSong song1 = new SerSong("Penny Lane", 2, 57);
ObjectOutputStream out = new ObjectOutputStream(new
FileOutputStream("song.dat"));
out.writeObject(song1);
out.close();
}
}
|
|
import java.io.*;
import support.*;
public class SaveSong
{
private static PrintWriter outFile;
public static void main(String[] args) throws IOException
{
Song song1 = new Song("Penny Lane", 2, 57);
outFile = new PrintWriter(new FileWriter("song.txt"));
outFile.println(song1.getName());
outFile.println(song1.getDuration());
outFile.close();
}
}
|
|
//---------------------------------------------------------------------
// SerSongsApp.java by Dale/Joyce/Weems Chapter 6
//
// Allows user to manage a song list.
// Uses the file songs.dat to store and retrieve song list info.
//----------------------------------------------------------------------
import java.util.*; // Scanner
import java.io.*; // streams
import ch06.serLists.*; // SerSongList
import support.*; // SerSong
public class SerSongsApp
{
public static void main(String[] args)
{
Scanner conIn = new Scanner(System.in);
final String FILENAME = "songs.dat";
String name; // song name
String listName; // name of the song list
int minutes; // song duration
int seconds; // song duration
int number; // song number
SerSongList songs; // list of songs
SerSong song; // a single song
String skip; // skip rest of input line after reading integer
try
{
// Obtain song information from file and display it.
ObjectInputStream in = new ObjectInputStream(new
FileInputStream(FILENAME));
songs = (SerSongList)in.readObject();
System.out.println(songs);
}
catch (Exception e)
{
// Create a new song list.
System.out.println("Because the " + FILENAME + " file does not exist or");
System.out.println("can't be used, a new song list will be created.\n");
System.out.print("Song list name: ");
listName = conIn.nextLine();
songs = new SerSongList(listName);
}
// Get song information from user.
System.out.print("\nSong name (press Enter to end): ");
name = conIn.nextLine();
while (!name.equals(""))
{
System.out.print("Minutes: ");
minutes = conIn.nextInt();
skip = conIn.nextLine();
System.out.print("Seconds: ");
seconds = conIn.nextInt();
skip = conIn.nextLine();
song = new SerSong(name, minutes, seconds);
System.out.print("Song number between 1 and " + (songs.getSize() + 1) + ": ");
number = conIn.nextInt();
skip = conIn.nextLine();
songs.add(number, song);
System.out.println();
System.out.println(songs);
System.out.println();
System.out.print("Song name (press Enter to end): ");
name = conIn.nextLine();
}
// Display results.
System.out.println();
System.out.println("This song list will be saved in " + FILENAME + ":\n");
System.out.println(songs);
System.out.println();
// Save list.
try
{
ObjectOutputStream out = new ObjectOutputStream(new
FileOutputStream(FILENAME));
out.writeObject(songs);
out.close();
}
catch (Exception e)
{
System.out.println("Unable to save song information.");
}
}
}
|
|
public class UseFigs
{
public static void main(String[] args)
{
Circle c1 = new Circle(5);
Circle c2 = new Circle(5);
Circle c3 = new Circle(15);
Circle c4 = null;
System.out.println(c1 == c1);
System.out.println(c1 == c2);
System.out.println(c1 == c3);
System.out.println(c1 == c4);
System.out.println(c1.equals(c1));
System.out.println(c1.equals(c2));
System.out.println(c1.equals(c3));
System.out.println(c1.equals(c4));
}
}
|
|
import ch06.lists.*;
public class UseLists
{
public static void main(String[] args)
{
ListInterface list1 = new ArrayUnsortedList(3);
list1.add("Wirth");
list1.add("Dykstra");
list1.add("DePasquale");
list1.add("Dahl");
list1.add("Nygaard");
list1.remove("DePasquale");
ListInterface list2 = new ArraySortedList(3);
list2.add("Wirth");
list2.add("Dykstra");
list2.add("DePasquale");
list2.add("Dahl");
list2.add("Nygaard");
list2.remove("DePasquale");
IndexedListInterface list3 = new ArrayIndexedList(3);
list3.add(0, "Wirth");
list3.add(0, "Dykstra");
list3.add(0, "DePasquale");
list3.add(3, "Dahl");
list3.add(2, "Nygaard");
list3.remove("DePasquale");
System.out.print("Unsorted ");
System.out.println(list1);
System.out.print("Sorted ");
System.out.println(list2);
System.out.print("Indexed ");
System.out.println(list3);
}
}
|