4 Replies - 260 Views - Last Post: 22 October 2011 - 04:58 PM Rate Topic: -----

#1 OhNoNotAgain  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 18
  • Joined: 08-September 11

Some Problems with NoDupCollection

Posted 22 October 2011 - 08:56 AM

You also are required to create a Java program called ClientForNoDupCollection that accepts the name of a text file as a command line argument. Your program should parse the given text file so that is recognizes and records unique words, numbers, and single character symbols but ignores all white space found in the file. The definitions of these categories are given below.

I am to create a no-argument constructor for NoDupCollection and to not support the constructor in BasicCollection that accepts a collection as an argument. Then I am to override the add method to not allow duplicates. Change the access modifies of the instance variables in BasicCollection and private methods to public methods.

Then I am to create a Java program called ClientForNoDupCollection that takes a file name through command line argument. My program should parse the text file so it recognizes unique words, numbers and single character symbols but ignores all white space.

import java.util.Collection;
import java.util.Iterator;
import java.util.*;

/**
 * A collection represents a group of objects, known as its
 *   <i>elements</i>. <code>BasicCollection</code> is a simple
 *   implementation of the <code>java.util.Collection</code>
 *   interface and has the following characteristics. It
 *  <UL> <li> allows duplicate elements</li>
 *       <li> disallows <code>null</code> elements</li>
 *       <li> is unordered</li>
 *       <li> has no fixed capacity</li>
 *  </UL>
 */
public class BasicCollection<E> extends java.util.AbstractCollection<E> implements
    Cloneable {

  protected static final int DEFAULT_SIZE = 100;
  /**
   * The array buffer into which the elements are stored.
   * The array is resized when an add() occurs and the
   * capacity of the array has been reached.
   */
  protected E[] collection;

  /**
   * The number of elements contained in this collection.
   */
  protected int size;

  /**
   * The number of add and remove operations performed on
   * this collection. This information is used by the iterator
   * to provide a fail-fast iterator. Any operation that changes
   * the size of this collection should add 1 to
   * <code>modcount</code> for <it>each</it> change made.
   */
  protected transient int modCount;

  /**
   * Constructs an empty collection.
   */
  protected BasicCollection() {
    collection = ( E[] ) ( new Object[DEFAULT_SIZE] );
    size = 0;
   modCount = 0;
  }

  /**
   * Constructs a collection containing the elements of the
   * specified collection.
   *
   * @param c the collection whose elements are to be placed
   *         into this collection.
   * @throws IllegalArgumentException - if <code>c</code>
   *          is <code>null</code>.
   */
  protected BasicCollection( Collection<? extends E> c ) {
    if ( c == null ) {
      throw new java.lang.IllegalArgumentException();
    }
    int size = c.size() > DEFAULT_SIZE ?
        ( c.size() * 110 ) / 100 : DEFAULT_SIZE;
    collection = ( E[] )new Object[size];
    c.toArray( collection );
    modCount = 0;
  }

  /**
   * Ensures that this collection contains the specified
   * element. The collection does not support <code>null</code>
   * elements.
   * <p>
   * Returns <code>true</code> if the collection is changed as
   * a result of the call.
   *
   * @param element the element whose presence in this collection
   *         is to be ensured.
   * @return <code>true</code> if the collection changed as a
   *         result of the call.
   * @throws IllegalArgumentException if the argument is
   *         <code>null</code>.
   */
  public boolean add( E element ) {
    if ( element == null ) {
      throw new java.lang.IllegalArgumentException();
    }
    // if the collection is at capacity, make it bigger by 50%
    if ( this.size == collection.length ) {
      resize( this.size + this.size / 2 );
    }
    collection[size] = element;
    size++;
    modCount++;
    
    return true;
  }

  /**
   * Removes a single instance of the specified element from this
   * collection, if it is present.
   *
   * @param <code>element</code> the element to be removed from
   *        the collection.
   * @return <code>true</code> if this collection changed as a
   *         result of the call (this can only be true if there
   *         was at least one instance of <code>element</code>
   *         in this collection).
   * @throws IllegalArgumentException if <code>element</code>
   *         is <code>null</code>.
   */
  public boolean remove( Object element ) {
    if ( element == null ) {
      throw new IllegalArgumentException();
    }
    int p = find( element );
    if ( p == -1 ) {
      return false;
    }
    for ( int i = p; i < size - 1; i++ ) {
      collection[i] = collection[i + 1];
    }
    collection[size - 1] = null; // be neat!

    // Comment out the next line to illustrate
    //  the behavior of JUnit when a test fails.
    size--;
    modCount++;
    return true;
  }

  /**
   * Creates and returns a copy of this object.
   *
   *  The following is true of the clone and the original:
   * <blockquote><pre>
   * x.clone() != x
   * x.clone().getClass() == x.getClass()
   * x.clone().equals(x)
   * </pre></blockquote>
   *
   * @return     a clone of this instance.
   * @exception  OutOfMemoryError if there is not enough memory
   * @see        java.lang.Cloneable
   */
  public Object clone() {
    BasicCollection<E> c = null;
    // 1. clone the entire collection object
    try {
      c = ( BasicCollection<E> )super.clone();
    }
    catch ( CloneNotSupportedException e ) {
      // shouldn't get here, so don't do anything
    }
    // 2. clone the collection array
    c.collection = ( E[] )this.collection.clone();
    return c;
    /*     // the following produces a shallow clone of the collection
            Object result = null;
            try {
            result = super.clone();
            }catch( CloneNotSupportedException e )
            { // shouldn't get here, so don't do anything
            }
            return result;
     */
  }

  /**
   * Returns the number of elements in this collection.
   *
   * @return the number of elements in this collection.
   */
  public int size() {
    return this.size;
  }

  /**
   * Returns an iterator over the elements contained in
   * this collection.
   * @return an iterator over the elements contained in
   *         this collection.
   */
  public Iterator<E> iterator() {
    return new BasicIterator();
  }

  protected void resize( int new_length ) {
    E[] temp = ( E[] )new Object[new_length];
    for ( int i = 0; i < collection.length; i++ ) {
      temp[i] = collection[i];
      collection[i] = null; // cleanup
    }
    collection = temp;
  }

  protected int find( Object element ) {
    for ( int i = 0; i < size; i++ ) {
      if ( element.equals( collection[i] ) ) {
        return i;
      }
    }
    return -1; // failure
  }

  protected class BasicIterator implements Iterator<E> {
    /**
     * cursor is used to access the next element in the
     * sequence. In its implementation, cursor is always
     * the index of the next element to return. So cursor
     * should be incremented _after_ retrieving the next
     * element in the sequence.
     */
    protected int cursor;

    /**
     * Provides fail-fast operation of the iterator. For each
     * call to an iterator method, expectedModcount should be
     * equal to the collection's modCount, otherwise an
     * intervening change (concurrent modification) to the
     * collection has been made and we cannot guarantee that
     * the iterator will behave correctly.
     */
    protected int expectedModcount;

    /**
     * the contract of remove() says that each call to
     * remove() must have been preceded by a call to next()
     * (they are paired). So if there has been NO call to
     * next() prior to a remove() or if there were two remove()
     * calls without an intervening next() call, it is NOT ok
     * to try to remove an item.
     */
    protected boolean okToRemove;

    public BasicIterator() {
      cursor = 0;
      expectedModcount = modCount;
      okToRemove = false;
    }

    /**
     * Determine if there are more elements in the iteration
     * sequence.
     * @returns boolean <code>true</code> if there are more
     *                  elements in the iteration sequence.
     */
    public boolean hasNext() {
      return cursor != size;
    }

    /**
     * Returns the next element in the iteration sequence.
     *
     * @returns Object next element in the iteration sequence
     * @throws ConcurrentModificationException if this
     *         collection has been modified by a method outside
     *         of this iterator.
     * @throws NoSuchElementException if hasNext() is false
     */
    public E next() {
      // check for concurrent modification
      if ( expectedModcount != modCount ) {
        throw
            new java.util.ConcurrentModificationException();
      }

      // check that there are more elements in the iterator
      // sequence
      if ( !hasNext() ) {
        throw new java.util.NoSuchElementException();
      }

      // indicate that we have met the contract
      // requirements for remove()
      okToRemove = true;

      // there are more elements to retrieve, so
      // 1. get the element in cursor's position
      // 2. advance the cursor to the next element
      E element = collection[cursor];
      cursor++;
      return element;
    }

    /**
     * remove the element returned by the last call to
     * <code>next()</code>.
     * @throws ConcurrentModificationException if this
     *         collection has been modified by a method
     *         outside of this iterator.
     * @throws IllegalStateException if there has been no
     *         call to next() for this iteration or if two
     *         calls to remove() have been made with no
     *         intervening call to next().
     */
    public void remove() {
      // check for concurrent modification
      if ( expectedModcount != modCount ) {
        throw
            new java.util.ConcurrentModificationException();
      }

      // check that there has been a next() message to
      // provide an element to remove
      if ( !okToRemove ) {
        throw new IllegalStateException();
      }

      okToRemove = false;

      // Use BasicCollection's remove() method to do the
      // actual removal. Need to predecrement cursor to
      // get to the LAST element returned by next(). After
      // the removal, this will be the value cursor should
      // have for the next call to next().
      --cursor;
      BasicCollection.this.remove( collection[cursor] );

      // increment expectedModcount since the remove()
      // message above to the collection object will
      // have incremented modCount
      expectedModcount++;
    }
  }
}



import java.util.*;

//Creates No Argument constructor and Overrides add from BasicCollection
public class NoDupCollection extends BasicCollection{
	
	public NoDupCollection(){};

	  public boolean add( NoDupCollection element ) {
		  	
		    if ( element == null ) {
		      throw new java.lang.IllegalArgumentException();
		    }
		    // if the collection is at capacity, make it bigger by 50%
		    if ( this.size == collection.length ) {
		      resize( this.size + this.size / 2 );
		    }
		    
		    if(this.contains(element)){
		   
		    	return false;
		    }
		    
		    collection[size] = element;
		    size++;
		    modCount++;
		    
		    return true;
		    
		  }
	
}




import java.util.*;
import java.io.*;

public class ClientForNoDupCollection extends NoDupCollection{

	public static void main(String[] args) {
		
		if(args == null){
			System.out.println("File Not Found");
		}
		
		BasicCollection<String> words = new NoDupCollection();
		BasicCollection<Integer> numbers = new NoDupCollection();
		BasicCollection<Character> special = new NoDupCollection();

		
		 File file = new File(args[0]);
		    if (!file.exists()) {
		      System.out.println(args[0] + " does not exist.");
		      return;
		    }
		    if (!(file.isFile() && file.canRead())) {
		      System.out.println(file.getName() + " cannot be read from.");
		      return;
		    }
		    try {
		      FileInputStream fis = new FileInputStream(file);
		      char current;
		      while (fis.available() > 0) {
		        current = (char) fis.read();
		        
		        if(Character.isLetter(current)){
		        	
		        String word =	Character.toString(current);
		        	words.add(word);
		        }
		        if(Character.isDigit(current)){
		        	int num = current - '0';
		        	numbers.add(num);
		        }
		        else{
		        
		        }
		      
		      }
		    } catch (IOException e) {
		      e.printStackTrace();
		    }
		
			
		System.out.println("Unique Word Collection:");
		
		Iterator<String> iter;
		for (iter = words.iterator(); iter.hasNext();)/>{
			System.out.println(iter.next());
		}	
		
		System.out.println("Unique Number Collection:");
		Iterator<Integer> iteri;
			for (iteri = numbers.iterator(); iteri.hasNext();)/>{
				System.out.println(iteri.next());
			}
		}
	}




The problem I am having is that the add method from NoDupCollection is no overriding the add from BasicCollection. I am also having trouble figuring out after testing if the current character is a letter or number if there are any others directly after it. Also not sure how to test if the current character being read is a symbol.

Example Input: This is a 1 test file.

Supposed to output:
Unique Word Collection:
This
is
a
test
file

Unique Number Collection:
1

Unique Special Character Collection:
.

Is This A Good Question/Topic? 0
  • +

Replies To: Some Problems with NoDupCollection

#2 macosxnerd101  Icon User is online

  • Self-Trained Economist
  • member icon




Reputation: 10193
  • View blog
  • Posts: 37,641
  • Joined: 27-December 08

Re: Some Problems with NoDupCollection

Posted 22 October 2011 - 12:22 PM

This is the output I got when running your code:

Quote

Unique Word Collection:
T
h
i
s
i
s
a
t
e
s
t
f
i
l
e
Unique Number Collection:
1


Why are you reading character by character? Why not just read the entire line and split() it on whitespace? You can test to see if a String is a number using the Integer.parseInt() method and a try-catch block. If the catch block is not executed, then the String is numeric.

Also, if you're good with regular expressions, you can filter symbols out of Strings.

A couple final notes. First, your Main class should not extend NoDupCollection. Second, since BasicCollection is generic, NoDupCollection should be defined generically as well.
Was This Post Helpful? 0
  • +
  • -

#3 OhNoNotAgain  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 18
  • Joined: 08-September 11

Re: Some Problems with NoDupCollection

Posted 22 October 2011 - 01:07 PM

Assignment says to, also when I read a word like there's. The program will add there to the string collection, ' to special character collection and add s to string collection.

If you know of a way I can solve this program with reading in character by character mind helping me in the right direction? I fixed the NoDupCollection, now it looks like this:

import java.util.*;

//Creates No Argument constructor and Overrides add from BasicCollection
public class NoDupCollection<E> extends BasicCollection<E>{
	
	public NoDupCollection(){};

	  public boolean add( E element ) {
		  	
		    if ( element == null ) {
		      throw new java.lang.IllegalArgumentException();
		    }
		    // if the collection is at capacity, make it bigger by 50%
		    if ( this.size == collection.length ) {
		      resize( this.size + this.size / 2 );
		    }
		    
		    if(this.contains(element)){
		   
		    	return false;
		    }
		    
		    collection[size] = element;
		    size++;
		    modCount++;
		    
		    return true;
		    


Thanks for your help and for any future help.

This post has been edited by macosxnerd101: 22 October 2011 - 01:41 PM
Reason for edit:: Removed quote

Was This Post Helpful? 0
  • +
  • -

#4 macosxnerd101  Icon User is online

  • Self-Trained Economist
  • member icon




Reputation: 10193
  • View blog
  • Posts: 37,641
  • Joined: 27-December 08

Re: Some Problems with NoDupCollection

Posted 22 October 2011 - 01:48 PM

What you'll want to do is check for whitespace. Until then, append all the letters to a single String (or StringBuilder, if you want to go the more memory efficient route). When you find a whitespace, append the String (or StringBuilder toString()) to the String Collection. Append all the numbers to the number Collection. And if it isn't a number or letter, append it to the specialCharacters Collection.

You will want to check out the Character class. It has methods like isLetter(), isNumber(), isLetterOrNumber(), and isWhitespace() that you will find helpful.
Was This Post Helpful? 0
  • +
  • -

#5 OhNoNotAgain  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 18
  • Joined: 08-September 11

Re: Some Problems with NoDupCollection

Posted 22 October 2011 - 04:58 PM

This is the code I have now:

import java.util.*;
import java.io.*;

public class ClientForNoDupCollection extends NoDupCollection{

	public static void main(String[] args) {
		String word = "";

		if(args.length != 1){
			System.err.println("File Not Found");
			System.exit(1);
		}
		BasicCollection<String> words = new NoDupCollection();
		BasicCollection<Integer> numbers = new NoDupCollection();
		BasicCollection<Character> special = new NoDupCollection();

		try {
			FileReader fr = new FileReader(args[0]);
			BufferedReader br = new BufferedReader(fr);
			int r;
			while((r =fr.read()) != -1){
				char ch = (char) r;
				if(Character.isLetter(ch)){
					word = word+ch;
				}
				words.add(word);
				if(Character.isDigit(ch)){
					int num = ch - '0';
					numbers.add(num);
				}	  
				else{
					if(Character.isWhitespace(ch)){
					}
					special.add(ch);
				}
			}
		
			fr.close();
		}
		catch(Exception e) {
			System.out.println("Exception: " + e);
		}

		System.out.println("Unique Word Collection:");

		Iterator<String> iter;
		for (iter = words.iterator(); iter.hasNext();)/>{
			System.out.println(iter.next());
		}	

		System.out.println("Unique Number Collection:");
		Iterator<Integer> iteri;
		for (iteri = numbers.iterator(); iteri.hasNext();)/>{
			System.out.println(iteri.next());

			System.out.println("Unique Symbols Collection:");
			Iterator<Character> iterc;
			for (iterc = special.iterator(); iterc.hasNext();)/>{
				System.out.println(iterc.next());
			}
		}
	}
}




But now I am having issues with it printing out as each letter goes on rather than just the word itself. Not sure what to do exactly at the point to where I need to test the item being tested.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1