Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

you will analyze and implement a StringArrayBag class which uses an array as its underlying data structure. You will also implement a cursor-style iterator to

you will analyze and implement a StringArrayBag class which uses an array as its underlying data structure.

You will also implement a cursor-style iterator to allow for iteration. This means that the StringArrayBag has been modified to implement both Iterable and Iterator, as it is its own iterator.

Implement countOccurrences method

import java.util.Iterator;

import java.util.NoSuchElementException;

import java.util.Vector;

/**

* Modified and stripped version of ArrayBag

* from

* http://www.cs.colorado.edu/~main/docs/

*

* It is important to note that we did not implement the following methods.

*

    *

  • clone
  • *

  • getCapacity
  • *

  • grab
  • *

  • remove
  • *

  • trimToSize
  • *

  • union
  • *

* Though it also important to note, that we have made ArrayBag now

* implement Iterable and Iterator to make ArrayBag have a cursor-style

* iterator, in other words, be its own iterator

*

* @author xiong239

*/

public class StringArrayBag implements Iterable, Iterator {

private final static int INITIAL_CAPACTIY = 10;

private String[] data;

private int manyItems;

/**

* Initializes a bag of INITIAL_CAPACITY

*/

public StringArrayBag() {

this(INITIAL_CAPACTIY);

}

/**

* Initializes a bag of the given initial capacity

* @param initialCapacity, initial capacity of the bag

*/

@SuppressWarnings("unchecked")

public StringArrayBag(int initialCapacity) {

if (initialCapacity < 0 ) throw new IllegalArgumentException("initialCapacity is negative: " + initialCapacity);

this.manyItems = 0;

this.data = new String[initialCapacity];

}

/**

* Add the element to end of the bag

* @param element, element to add

* @throws IllegalArgumentException, if element is null

*/

public void add(String element) {

if (element == null) throw new IllegalArgumentException("element cannot be null");

ensureCapacity(this.manyItems+1);

this.data[manyItems++] = element;

}

/**

* Add many elements to the end of the bag in the order they are passed

* @param elements, elements to add to the end of the bag

* @throws IllegalArgumentException, if any element of the elements is null

*/

@SuppressWarnings("unchecked")

public void addMany(String... elements) {

for (String element : elements) {

if (element == null) throw new IllegalArgumentException("there cannot be a null element");

}

ensureCapacity(this.manyItems+elements.length);

System.arraycopy(elements, 0, this.data, this.manyItems, elements.length);

this.manyItems += elements.length;

}

/**

* Counts the occurrences of the target in the bag

* @param target, the element to count the occurrences of

* @return number of times the target appears in the bag

* @throws IllegalArgumentException, if the target is null

*/

public int countOccurrences(String target) {

if (target == null) throw new IllegalArgumentException("target cannot be null");

int answer = 0;

// TODO for a given target, loop through your elements

// and count the times it shows. DO NOT use an iterator

// as an internal iterator will reset other iterators

return answer;

}

/**

* Counts the occurrences of the target in the bag

* This version uses the iterator to count the occurrences

* @param target, the element to count the occurrences of

* @return number of times the target appears in the bag

* @throws IllegalArgumentException, if the target is null

*/

public int countOccurrencesWithIterator(String target) {

if (target == null) throw new IllegalArgumentException("target cannot be null");

int answer = 0;

// TODO for a given target, loop through your elements

// and count the times it shows. DO NOT use an iterator

// as an internal iterator will reset other iterators

return answer;

}

/**

* Ensures the bag can hold the minimum capacity given, and

* resizes if needed to the minimum capacity.

* @param minimumCapacity

*/

@SuppressWarnings("unchecked")

public void ensureCapacity(int minimumCapacity) {

if (this.data.length < minimumCapacity)

{

String[] biggerArray = new String[minimumCapacity];

System.arraycopy(this.data, 0 , biggerArray, 0, this.manyItems);

this.data = biggerArray;

}

}

/**

* Returns the size of the bag, or number of elements in the bag

* @return size of the bag

*/

public int size() {

return manyItems;

}

/**

* Prints the contents of the bag, along with its occurrences to console

* in the following format:

* element: occurrences

*/

public void printOccurrences() {

Vector printed = new Vector();

for (String element : this) {

if (!printed.contains(element)) {

System.out.printf("%s: %d ",element.toString(), this.countOccurrences(element));

printed.add(element);

}

}

}

/**

* Prints the contents of the bag, along with its occurrences to console

* this method uses the iterator

* in the following format:

* element: occurrences

*/

public void printOccurrencesWithIterator() {

Vector printed = new Vector();

for (String element : this) {

if (!printed.contains(element)) {

System.out.printf("%s: %d ",element.toString(), this.countOccurrencesWithIterator(element));

printed.add(element);

}

}

}

/************************************************

* Iterator Methods

************************************************/

// Tracks the index of the current element of the iterator

private int currentIndex = -1;

/**

* Prepares the internal iterator for iteration

*/

@Override

public Iterator iterator() {

this.currentIndex = -1;

return this;

}

/**

* Checks to see if there is a next element

*/

@Override

public boolean hasNext() {

return this.currentIndex + 1 < this.manyItems;

}

/**

* Fetches and returns the next element

*/

@Override

public String next() {

if (!hasNext()) throw new NoSuchElementException("There is no next element");

String nextElement = null;

// TODO Using the fields above, move to the next element and return it

return nextElement;

}

/**

* Removes the current element if there is one

*

* We will leave this method to the homework

*/

@Override

public void remove() {

throw new UnsupportedOperationException("cannot remove element from bag");

}

}

Using Eclipse, import ``Lab3'':

/afs/cs.uwm.edu/users/classes/cs351/401/

pantherid

/git/lab3.git

The countOccurrences is similar to the previous implementation. There are some subtle differences. The first change is that you should no longer accept null elements. This has been done for you already but should be noted. The second is that you have to use the equals method when comparing two String objects. For example:

string1.equals( string2 ) 

Do not use any iterator methods to implement this method.

After implementing countOccurrences, run TestArrayBag.java and ensure the tests for countOccurrences pass (except for testCountOccurrencesWithIterator).

Implement Iterator methods

You are given a field currentIndex in the iterator section of StringArrayBag. Implement the method next, and make any other modifications necessary to the iterator so that all tests pass.

The next method should, assuming a next element exists, point the iterator to the new current element and return that value. If no such element exists, an appropriate exception should be raised. We start at -1 for currentIndex because we don't have a current element until next is called.

Implement countOccurrencesWithIterator method

Write the countoccurrencesWithIterator method to make use of the iterator methods instead of accessing the data array directly. You can use the enhanced for loop to use these methods indirectly. Note how this type of loop is used in printOccurrences:

for (String element : this) 

Use a similar loop to implement countOccurrencesWithIterator with the iterator methods. You should now pass testCountOccurrencesWithIterator;

Using ArrayBag

Complete ArrayBagDriver, which will open a given file ( document.txt by default) and add each word to a StringArrayBag. After adding each word, the driver should call the printOccurrences and printOccurrencesWithIterator method to print the number of occurrences of each word in the document. You should take a look at these two printing methods to see how they differ.

The document.txt file simply contains the text to be or not to be, which should give the output:

to: 2 be: 2 or: 1 not: 1 

The output from the printOccurrences method should look like this. However, the output from printOccurrencesWithIterator should not. Note that the both printing methods use the enhanced for loop, which makes use of the iterator methods. printOccurrencesWithIterator also calls countOccurrencesWithIterator, which itself also uses the iterator methods.

package edu.uwm.cs351;

import java.util.Iterator;

import java.util.NoSuchElementException;

import java.util.Vector;

/**

* Modified and stripped version of ArrayBag

* from

* http://www.cs.colorado.edu/~main/docs/

*

* It is important to note that we did not implement the following methods.

*

    *

  • clone
  • *

  • getCapacity
  • *

  • grab
  • *

  • remove
  • *

  • trimToSize
  • *

  • union
  • *

* Though it also important to note, that we have made ArrayBag now

* implement Iterable and Iterator to make ArrayBag have a cursor-style

* iterator, in other words, be its own iterator

*

* @author xiong239

*/

public class StringArrayBag implements Iterable, Iterator {

private final static int INITIAL_CAPACTIY = 10;

private String[] data;

private int manyItems;

/**

* Initializes a bag of INITIAL_CAPACITY

*/

public StringArrayBag() {

this(INITIAL_CAPACTIY);

}

/**

* Initializes a bag of the given initial capacity

* @param initialCapacity, initial capacity of the bag

*/

@SuppressWarnings("unchecked")

public StringArrayBag(int initialCapacity) {

if (initialCapacity < 0 ) throw new IllegalArgumentException("initialCapacity is negative: " + initialCapacity);

this.manyItems = 0;

this.data = new String[initialCapacity];

}

/**

* Add the element to end of the bag

* @param element, element to add

* @throws IllegalArgumentException, if element is null

*/

public void add(String element) {

if (element == null) throw new IllegalArgumentException("element cannot be null");

ensureCapacity(this.manyItems+1);

this.data[manyItems++] = element;

}

/**

* Add many elements to the end of the bag in the order they are passed

* @param elements, elements to add to the end of the bag

* @throws IllegalArgumentException, if any element of the elements is null

*/

@SuppressWarnings("unchecked")

public void addMany(String... elements) {

for (String element : elements) {

if (element == null) throw new IllegalArgumentException("there cannot be a null element");

}

ensureCapacity(this.manyItems+elements.length);

System.arraycopy(elements, 0, this.data, this.manyItems, elements.length);

this.manyItems += elements.length;

}

/**

* Counts the occurrences of the target in the bag

* @param target, the element to count the occurrences of

* @return number of times the target appears in the bag

* @throws IllegalArgumentException, if the target is null

*/

public int countOccurrences(String target) {

if (target == null) throw new IllegalArgumentException("target cannot be null");

int answer = 0;

// TODO for a given target, loop through your elements

// and count the times it shows. DO NOT use an iterator

// as an internal iterator will reset other iterators

return answer;

}

/**

* Counts the occurrences of the target in the bag

* This version uses the iterator to count the occurrences

* @param target, the element to count the occurrences of

* @return number of times the target appears in the bag

* @throws IllegalArgumentException, if the target is null

*/

public int countOccurrencesWithIterator(String target) {

if (target == null) throw new IllegalArgumentException("target cannot be null");

int answer = 0;

// TODO for a given target, loop through your elements

// and count the times it shows. DO NOT use an iterator

// as an internal iterator will reset other iterators

return answer;

}

/**

* Ensures the bag can hold the minimum capacity given, and

* resizes if needed to the minimum capacity.

* @param minimumCapacity

*/

@SuppressWarnings("unchecked")

public void ensureCapacity(int minimumCapacity) {

if (this.data.length < minimumCapacity)

{

String[] biggerArray = new String[minimumCapacity];

System.arraycopy(this.data, 0 , biggerArray, 0, this.manyItems);

this.data = biggerArray;

}

}

/**

* Returns the size of the bag, or number of elements in the bag

* @return size of the bag

*/

public int size() {

return manyItems;

}

/**

* Prints the contents of the bag, along with its occurrences to console

* in the following format:

* element: occurrences

*/

public void printOccurrences() {

Vector printed = new Vector();

for (String element : this) {

if (!printed.contains(element)) {

System.out.printf("%s: %d ",element.toString(), this.countOccurrences(element));

printed.add(element);

}

}

}

/**

* Prints the contents of the bag, along with its occurrences to console

* this method uses the iterator

* in the following format:

* element: occurrences

*/

public void printOccurrencesWithIterator() {

Vector printed = new Vector();

for (String element : this) {

if (!printed.contains(element)) {

System.out.printf("%s: %d ",element.toString(), this.countOccurrencesWithIterator(element));

printed.add(element);

}

}

}

/************************************************

* Iterator Methods

************************************************/

// Tracks the index of the current element of the iterator

private int currentIndex = -1;

/**

* Prepares the internal iterator for iteration

*/

@Override

public Iterator iterator() {

this.currentIndex = -1;

return this;

}

/**

* Checks to see if there is a next element

*/

@Override

public boolean hasNext() {

return this.currentIndex + 1 < this.manyItems;

}

/**

* Fetches and returns the next element

*/

@Override

public String next() {

if (!hasNext()) throw new NoSuchElementException("There is no next element");

String nextElement = null;

// TODO Using the fields above, move to the next element and return it

return nextElement;

}

/**

* Removes the current element if there is one

*

* We will leave this method to the homework

*/

@Override

public void remove() {

throw new UnsupportedOperationException("cannot remove element from bag");

}

}

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Database And Expert Systems Applications 33rd International Conference Dexa 2022 Vienna Austria August 22 24 2022 Proceedings Part 2 Lncs 13427

Authors: Christine Strauss ,Alfredo Cuzzocrea ,Gabriele Kotsis ,A Min Tjoa ,Ismail Khalil

1st Edition

3031124251, 978-3031124259

More Books

Students also viewed these Databases questions