The main goal of Lab 7 is for the students to apply a collection class to a simple problem.
Here is the ArrayBag class:
public class ArrayBag implements Cloneable
{
private Object[ ] data;
private int manyItems;
public ArrayBag( )
{
final int INITIAL_CAPACITY = 10;
manyItems = 0;
data = new Object[INITIAL_CAPACITY];
}
public ArrayBag(int initialCapacity)
{
if (initialCapacity < 0)
throw new IllegalArgumentException
("The initialCapacity is negative: " + initialCapacity);
data = new Object[initialCapacity];
manyItems = 0;
}
public void add(Object element)
{
if (manyItems == data.length)
{
ensureCapacity(manyItems*2 + 1);
}
data[manyItems] = element;
manyItems++;
}
public void addAll(ArrayBag addend)
{
ensureCapacity(manyItems + addend.manyItems);
System.arraycopy(addend.data, 0, data, manyItems, addend.manyItems);
manyItems += addend.manyItems;
}
public Object clone( )
{ // Clone an ArrayBag object.
ArrayBag answer;
try
{
answer = (ArrayBag) super.clone( );
}
catch (CloneNotSupportedException e)
{
throw new RuntimeException
("This class does not implement Cloneable");
}
answer.data = (Object [ ]) data.clone( );
return answer;
}
public int countOccurrences(Object target)
{
int answer;
int index;
answer = 0;
if (target == null)
{ // Count how many times null appears in the bag.
for (index = 0; index < manyItems; index++)
if (data[index] == null)
answer++;
}
else
{ // Use target.equals to determine how many times the target appears.
for (index = 0; index < manyItems; index++)
if (target.equals(data[index]))
answer++;
}
return answer;
}
public void ensureCapacity(int minimumCapacity)
{
Object biggerArray[ ];
if (data.length < minimumCapacity)
{
biggerArray = new Object[minimumCapacity];
System.arraycopy(data, 0, biggerArray, 0, manyItems);
data = biggerArray;
}
}
public int getCapacity( )
{
return data.length;
}
public Object grab( )
{
int i;
if (manyItems == 0)
throw new IllegalStateException("Bag size is zero");
i = (int)(Math.random( ) * manyItems); // In range of 0 to manyItems-1
return data[i];
}
public Object grab(int pos)
{
if (manyItems == 0)
throw new IllegalStateException("Bag size is zero");
if(pos < 0 || pos > manyItems)
throw new IllegalArgumentException("Invalid index");
return data[pos];
}
public boolean remove(Object target)
{
int index; // The location of target in the data array.
if (target == null)
{ // Find the first occurrence of the null reference in the bag.
for (index = 0; (index < manyItems) && (data[index] != null); index++)
// No work is needed in the body of this for-loop.
;
}
else
{ // Use target.equals to find the first occurrence of the target.
for (index = 0; (index < manyItems) && (!target.equals(data[index])); index++)
// No work is needed in the body of this for-loop.
;
}
if (index == manyItems)
// The target was not found, so nothing is removed.
return false;
else
{ // The target was found at data[index].
// So reduce manyItems by 1 and copy the last element onto data[index].
manyItems--;
data[index] = data[manyItems];
return true;
}
}
public int size( )
{
return manyItems;
}
public void trimToSize( )
{
Object trimmedArray[ ];
if (data.length != manyItems)
{
trimmedArray = new Object[manyItems];
System.arraycopy(data, 0, trimmedArray, 0, manyItems);
data = trimmedArray;
}
}
public static ArrayBag union(ArrayBag b1, ArrayBag b2)
{
ArrayBag answer = new ArrayBag(b1.getCapacity( ) + b2.getCapacity( ));
System.arraycopy(b1.data, 0, answer.data, 0, b1.manyItems);
System.arraycopy(b2.data, 0, answer.data, b1.manyItems, b2.manyItems);
answer.manyItems = b1.manyItems + b2.manyItems;
return answer;
}
}
Here is the EasyReader class:
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.PushbackReader;
public class EasyReader extends PushbackReader
{
final static int EOF_VALUE = -1; // Returned by read( ) at EOF
final static char ZERO_CHAR = '\0'; // Unicode character zero
private boolean formatProblem = false;
public EasyReader(InputStream in)
{
super(new InputStreamReader(in));
}
public EasyReader(String name)
{
super(makeFileReader(name));
}
public EasyReader(InputStreamReader isr)
{
super(isr);
}
public char charInput( )
{
readSpaces( );
return readChar( );
}
public char charInputLine( )
{
char answer = charInput( );
skipLine( );
return answer;
}
public char charQuery(String prompt)
{
char answer;
System.out.print(prompt);
return charInputLine( );
}
public double doubleInput( )
{
final char POINT = '.';
StringBuffer input = new StringBuffer( );
readSpaces( );
input.append(readSign( ));
input.append(readDigits( ));
if (peek( ) == POINT)
{ // Read the decimal point and fractional part.
input.append(readChar( ));
input.append(readDigits( ));
}
if (Character.toUpperCase(peek( )) == 'E')
{ // Read the E and exponent.
input.append(readChar( ));
input.append(readSign( ));
input.append(readDigits( ));
}
try
{
formatProblem = false;
return Double.valueOf(input.toString( )).doubleValue( );
}
catch (NumberFormatException e)
{
formatProblem = true;
return Double.NaN;
}
}
public double doubleInputLine( )
{
double answer = doubleInput( );
skipLine( );
return answer;
}
public double doubleQuery(String prompt)
{
double answer;
System.out.print(prompt);
answer = doubleInputLine( );
while (formatProblem)
{
System.out.print("Invalid response. Please type a double value: ");
if (isEOF( ))
return Double.NaN;
answer = doubleInputLine( );
}
return answer;
}
private static void handleException(Exception e)
// Print an error message and halt the program.
{
System.err.println("Exception:" + e);
System.err.println("EasyReader will cause program to halt.");
System.exit(0);
}
public void ignore( )
{
readChar( );
}
public int intInput( )
{
String input = null;
readSpaces( );
input = readSign( ) + readDigits( );
try
{
formatProblem = false;
return Integer.parseInt(input);
}
catch (NumberFormatException e)
{
formatProblem = true;
return Integer.MIN_VALUE;
}
}
public int intInputLine( )
{
int answer = intInput( );
skipLine( );
return answer;
}
public int intQuery(String prompt)
{
int answer;
System.out.print(prompt);
answer = intInputLine( );
while (formatProblem)
{
System.out.print("Invalid response. Please type an integer value: ");
if (isEOF( ))
return Integer.MIN_VALUE;
answer = intInputLine( );
}
return answer;
}
public boolean isEOF( )
{
return (readAhead( ) == EOF_VALUE);
}
public boolean isEOLN( )
{
int next = readAhead( );
return (next == '\n') || (next == '\r') || (next == EOF_VALUE);
}
public boolean isFormatProblem( )
{
return formatProblem;
}
private static FileReader makeFileReader(String name)
{
try
{
return new FileReader(name);
}
catch (FileNotFoundException e)
{
handleException(e);
return null;
}
}
public static void pause(long milliseconds)
{
try
{
Thread.sleep(milliseconds);
}
catch (InterruptedException e)
{
// Resume execution
}
}
public char peek( )
{
int next = readAhead( );
if (next == EOF_VALUE)
return ZERO_CHAR;
else
return (char) next;
}
public boolean query(String prompt)
{
String answer;
System.out.print(prompt + " [Y or N] ");
answer = stringInputLine( ).toUpperCase( );
while (!answer.startsWith("Y") && !answer.startsWith("N"))
{
System.out.print("Invalid response. Please type Y or N: ");
if (isEOF( ))
return false;
answer = stringInputLine( ).toUpperCase( );
}
return answer.startsWith("Y");
}
private int readAhead( )
// Peek ahead and return the next character (or -1 for EOF).
{
int next = EOF_VALUE;
try
{
next = read( );
if (next == EOF_VALUE)
{
pause(1000);
}
else
unread(next);
}
catch (IOException e)
{
handleException(e);
}
return next;
}
private char readChar( )
// Read and return the next character (or -1 for EOF).
{
int next = EOF_VALUE;
try
{
next = read( );
if (next == EOF_VALUE)
{
next = ZERO_CHAR;
pause(1000);
}
}
catch (IOException e)
{
handleException(e);
}
return (char) next;
}
private String readDigits( )
// Read a sequence of digits and return the sequence as a String.
{
StringBuffer buffer = new StringBuffer( );
while (Character.isDigit(peek( )))
buffer.append(readChar( ));
return buffer.toString( );
}
private String readSign( )
// Read a + or - sign (if one is present) and return the read characters as a string.
{
StringBuffer buffer = new StringBuffer(1);
char possibleSign;
possibleSign = peek( );
if ((possibleSign == '-') || (possibleSign == '+'))
buffer.append(readChar( ));
return buffer.toString( );
}
private String readSpaces( )
// Read a sequence of whitespace characters and return the sequence as a String.
{
StringBuffer buffer = new StringBuffer( );
while (Character.isWhitespace(peek( )))
buffer.append(readChar( ));
return buffer.toString( );
}
public void skipLine( )
{
while (!isEOLN( ))
readChar( );
if (peek( ) == '\r')
readChar( );
if (peek( ) == '\n')
readChar( );
}
public String stringInput( )
{
StringBuffer buffer = new StringBuffer( );
formatProblem = false;
readSpaces( );
while (!isEOF( ) && !Character.isWhitespace(peek( )))
buffer.append(readChar( ));
return buffer.toString( );
}
public String stringInputLine( )
{
StringBuffer buffer = new StringBuffer( );
while (!isEOLN( ) && !isEOF( ))
buffer.append(readChar( ));
skipLine( );
return buffer.toString( );
}
public String stringQuery(String prompt)
{
System.out.print(prompt);
return stringInputLine( );
}
public static void main(String[ ] args)
{
EasyReader stdin = new EasyReader(System.in);
double d = stdin.doubleQuery("Double: ");
if (stdin.isFormatProblem( ))
System.out.println("A format error resulted in " + d);
else
System.out.println(d + " is a fine double number.");
int i = stdin.intQuery("Int: ");
if (stdin.isFormatProblem( ))
System.out.println("A format error resulted in " + i);
else
System.out.println(i + " is a fine integer.");
String s = stdin.stringQuery("String: ");
if (stdin.isFormatProblem( ))
System.out.println("A format error resulting in " + s);
else
System.out.println('"' + s + '"' + " is a fine String.");
int sum = 0;
System.out.println("Type one int per line & press ctrl-z to end:");
while (!stdin.isEOF( ))
sum += stdin.intInputLine( );
System.out.println("Total sum: " + sum);
}
}
Here is the ChoreList program:
public class ChoreList
{
private static EasyReader stdin = new EasyReader(System.in);
private static ArrayBag chores = new ArrayBag();
private static int option;
private static int cursor;
public static void prompt()
{
System.out.println("Enter 1 ITEM to add ITEM to the list of chores");
System.out.println("Enter 2 to ask how many chores are in the list");
System.out.println("Enter 3 to print the list of chores");
System.out.println("Enter 4 ITEM to delete ITEM from the list");
System.out.println("Enter 5 to exit");
System.out.println();
}
public static boolean tokenize(String input)
{
int len = input.length();
// remove leading space
for(cursor = 0; cursor < len; cursor++) {
if(!Character.isWhitespace(input.charAt(cursor))) {
break;
}
}
// illegal input format:
// input just contains white space or the current char is not
// digit or the current char followed by another character which
// is not a whitespace
if(cursor == len) {
return false;
}
else if(!Character.isDigit(input.charAt(cursor))) {
return false;
}
else if(cursor + 1 < len &&
!Character.isWhitespace(input.charAt(cursor + 1))) {
return false;
}
try {
option = Integer.parseInt(input.substring(cursor,cursor+1));
}
catch (Exception e) {
return false;
}
return true;
}
public static void main(String[] args)
{
String input = null;
String item = null;
boolean bye = false;
prompt();
while(!bye) {
input = stdin.stringInputLine();
if(!tokenize(input)) {
System.out.println("Invalid response");
prompt();
continue;
}
switch(option) {
// To be completed by the student
}
}
}
}