Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

Study the BagApplet from Appendix I and write an expanded version that tests methods equals, toString, removeAll, and intersecdtion of IntArray Bag class. More specifically,

Study the BagApplet from Appendix I and write an expanded version that tests methods equals, toString, removeAll, and intersecdtion of IntArray Bag class. More specifically, it should have two bags (b1 and b2) and the following buttons: Buttons to activate methods add, remove, toString of any of the two bags. There should be also a text area where a user can enter an element. Each button must perform correct action when clicked. When an add button is clicked, the element entered by the user in the text area should be added to the specified bag. When a remove button is clicked, the element entered by the user in the text area should be removed from the bag if it is in the bag. If the element is not in the bag, then a message saying that the element is not in the bag should appear in the feedback text area. When a button is clicked a message about performed action should appear in the feedback text area. For instance, when b1.add() is clicked with element 5 in the text area, the following message should appear in the feedback text area: 5 has been added to b1. A button that will carry out the action b1.equals(b2). When the button is pressed a message should appear in the feedback area saying whether the bags are equal or not. A button that will carry out the action b1.removeAll(b2) and another button that would carry out the action b2.removeAll(b1). When any of these buttons is pressed a message about performed action should appear in the feedback area. A button that will carry out the action intersection(b1, b2). When the button is pressed a message should appear in the feedback area displaying a bag that is an intersection of b1 and b2. For instance if b1 is {2, 3, 3, 4} and b2 is {3, 4, 4, 5} then a message like the following should be displayed: Intersection of b1 and b2 is {4, 3}.

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

* An IntArrayBag is a collection of int numbers.

* The same number may appear multiple times in a bag.

*

* @note

* (1) The capacity of one of these bags can change after it's created, but

* the maximum capacity is limited by the amount of free memory on the

* machine. The constructor, addItem, clone,

* and union will result in an OutOfMemoryError

* when free memory is exhausted.

*

* (2) A bag's capacity cannot exceed the maximum integer 2,147,483,647

* (Integer.MAX_VALUE). Any attempt to create a larger capacity

* results in a failure due to an arithmetic overflow.

*

* (3) Because of the slow linear algorithms of this

* class, large bags will have poor performance.

*

* @see

*

* Java Source Code for this class

* (www.cs.colorado.edu/~main/edu/colorado/collections/IntArrayBag.java)

*

*

* @author Michael Main

* (main@colorado.edu)

*

* @version

* Jul 5, 2005

*

* @see ArrayBag

* @see IntLinkedBag

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

class TestMain{

public static void main(String args[]){

IntArrayBag b1=new IntArrayBag();

IntArrayBag b2=new IntArrayBag();

b1.add(4);b1.add(4);b1.add(7);b1.add(7);b1.add(7);b1.add(8);b1.add(1);

b2.add(4);b2.add(7);b2.add(6);b2.add(1);

System.out.println("B1:"+b1.toString());

System.out.println("B2:"+b2.toString());

IntArrayBag b3=IntArrayBag.intersection(b1,b2);

System.out.println("B3:"+b3.toString());

IntArrayBag b4=IntArrayBag.intersection(b1,b2);

System.out.println("B4:"+b4.toString());

System.out.println("B4==B3:"+b3.equals(b4));

System.out.println("B1==B2:"+b1.equals(b2));

}

}

public class IntArrayBag implements Cloneable

{

// Invariant of the IntArrayBag class:

// 1. The number of elements in the bag is in the instance variable

// manyItems, which is no more than data.length.

// 2. For an empty bag, we do not care what is stored in any of data;

// for a non-empty bag, the elements in the bag are stored in data[0]

// through data[manyItems-1], and we don?t care what?s in the

// rest of data.

private int[ ] data;

private int manyItems;

/**

* Initialize an empty bag with an initial capacity of 10. Note that the

* addItem method works efficiently (without needing more

* memory) until this capacity is reached.

* @param - none

* @postcondition

* This bag is empty and has an initial capacity of 10.

* @exception OutOfMemoryError

* Indicates insufficient memory for:

* new int[10].

**/

public IntArrayBag( )

{

final int INITIAL_CAPACITY = 10;

manyItems = 0;

data = new int[INITIAL_CAPACITY];

}

/**

* Initialize an empty bag with a specified initial capacity. Note that the

* addItem method works efficiently (without needing more

* memory) until this capacity is reached.

* @param initialCapacity

* the initial capacity of this bag

* @precondition

* initialCapacity is non-negative.

* @postcondition

* This bag is empty and has the given initial capacity.

* @exception IllegalArgumentException

* Indicates that initialCapacity is negative.

* @exception OutOfMemoryError

* Indicates insufficient memory for: new int[initialCapacity].

**/

public IntArrayBag(int initialCapacity)

{

if (initialCapacity < 0)

throw new IllegalArgumentException

("The initialCapacity is negative: " + initialCapacity);

data = new int[initialCapacity];

manyItems = 0;

}

/**

* Add a new element to this bag. If the new element would take this

* bag beyond its current capacity, then the capacity is increased

* before adding the new element.

* @param element

* the new element that is being inserted

* @postcondition

* A new copy of the element has been added to this bag.

* @exception OutOfMemoryError

* Indicates insufficient memory for increasing the bag's capacity.

* @note

* An attempt to increase the capacity beyond

* Integer.MAX_VALUE will cause the bag to fail with an

* arithmetic overflow.

**/

public void add(int element)

{

if (manyItems == data.length)

{ // Ensure twice as much space as we need.

ensureCapacity((manyItems + 1)*2);

}

data[manyItems] = element;

manyItems++;

}

/**

* Add new elements to this bag. If the new elements would take this

* bag beyond its current capacity, then the capacity is increased

* before adding the new elements.

* @param elements

* (a variable-arity argument)

* one or more new elements that are being inserted

* @postcondition

* A new copy of the element has been added to this bag.

* @exception OutOfMemoryError

* Indicates insufficient memory for increasing the bag's capacity.

* @note

* An attempt to increase the capacity beyond

* Integer.MAX_VALUE will cause the bag to fail with an

* arithmetic overflow.

**/

public void addMany(int... elements)

{

if (manyItems + elements.length > data.length)

{ // Ensure twice as much space as we need.

ensureCapacity((manyItems + elements.length)*2);

}

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

manyItems += elements.length;

}

/**

* Add the contents of another bag to this bag.

* @param addend

* a bag whose contents will be added to this bag

* @precondition

* The parameter, addend, is not null.

* @postcondition

* The elements from addend have been added to this bag.

* @exception NullPointerException

* Indicates that addend is null.

* @exception OutOfMemoryError

* Indicates insufficient memory to increase the size of the bag.

* @note

* An attempt to increase the capacity beyond

* Integer.MAX_VALUE will cause an arithmetic overflow

* that will cause the bag to fail. Such large collections should use

* a different bag implementation.

**/

public void addAll(IntArrayBag addend)

{

// If addend is null, then a NullPointerException is thrown.

// In the case that the total number of items is beyond

// Integer.MAX_VALUE, there will be an arithmetic overflow and

// the bag will fail.

ensureCapacity(manyItems + addend.manyItems);

System.arraycopy(addend.data, 0, data, manyItems, addend.manyItems);

manyItems += addend.manyItems;

}

/**

* Generate a copy of this bag.

* @param - none

* @return

* The return value is a copy of this bag. Subsequent changes to the

* copy will not affect the original, nor vice versa.

* @exception OutOfMemoryError

* Indicates insufficient memory for creating the clone.

**/

public IntArrayBag clone( )

{ // Clone an IntArrayBag object.

IntArrayBag answer;

try

{

answer = (IntArrayBag) super.clone( );

}

catch (CloneNotSupportedException e)

{ // This exception should not occur. But if it does, it would probably

// indicate a programming error that made super.clone unavailable.

// The most common error would be forgetting the "Implements Cloneable"

// clause at the start of this class.

throw new RuntimeException

("This class does not implement Cloneable");

}

answer.data = data.clone( );

return answer;

}

/**

* Accessor method to count the number of occurrences of a particular element

* in this bag.

* @param target

* the element that needs to be counted

* @return

* the number of times that target occurs in this bag

**/

public int countOccurrences(int target)

{

int answer;

int index;

answer = 0;

for (index = 0; index < manyItems; index++)

if (target == data[index])

answer++;

return answer;

}

/**

* Change the current capacity of this bag.

* @param minimumCapacity

* the new capacity for this bag

* @postcondition

* This bag's capacity has been changed to at least minimumCapacity.

* If the capacity was already at or greater than minimumCapacity,

* then the capacity is left unchanged.

* @exception OutOfMemoryError

* Indicates insufficient memory for: new int[minimumCapacity].

**/

public void ensureCapacity(int minimumCapacity)

{

int[ ] biggerArray;

if (data.length < minimumCapacity)

{

biggerArray = new int[minimumCapacity];

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

data = biggerArray;

}

}

/**

* Accessor method to get the current capacity of this bag.

* The add method works efficiently (without needing

* more memory) until this capacity is reached.

* @param - none

* @return

* the current capacity of this bag

**/

public int getCapacity( )

{

return data.length;

}

/**

* Remove one copy of a specified element from this bag.

* @param target

* the element to remove from the bag

* @postcondition

* If target was found in the bag, then one copy of

* target has been removed and the method returns true.

* Otherwise the bag remains unchanged and the method returns false.

**/

public boolean remove(int target)

{

int index; // The location of target in the data array.

// First, set index to the location of target in the data array,

// which could be as small as 0 or as large as manyItems-1; If target

// is not in the array, then index will be set equal to manyItems;

for (index = 0; (index < manyItems) && (target != 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;

}

}

/**

* Determine the number of elements in this bag.

* @param - none

* @return

* the number of elements in this bag

**/

public int size( )

{

return manyItems;

}

/**

* Reduce the current capacity of this bag to its actual size (i.e., the

* number of elements it contains).

* @param - none

* @postcondition

* This bag's capacity has been changed to its current size.

* @exception OutOfMemoryError

* Indicates insufficient memory for altering the capacity.

**/

public void trimToSize( )

{

int[ ] trimmedArray;

if (data.length != manyItems)

{

trimmedArray = new int[manyItems];

System.arraycopy(data, 0, trimmedArray, 0, manyItems);

data = trimmedArray;

}

}

/**

* Create a new bag that contains all the elements from two other bags.

* @param b1

* the first of two bags

* @param b2

* the second of two bags

* @precondition

* Neither b1 nor b2 is null, and

* b1.getCapacity( ) + b2.getCapacity( ) <= Integer.MAX_VALUE.

* @return

* the union of b1 and b2

* @exception NullPointerException.

* Indicates that one of the arguments is null.

* @exception OutOfMemoryError

* Indicates insufficient memory for the new bag.

* @note

* An attempt to create a bag with a capacity beyond

* Integer.MAX_VALUE will cause an arithmetic overflow

* that will cause the bag to fail. Such large collections should use

* a different bag implementation.

**/

public static IntArrayBag union(IntArrayBag b1, IntArrayBag b2)

{

// If either b1 or b2 is null, then a NullPointerException is thrown.

// In the case that the total number of items is beyond

// Integer.MAX_VALUE, there will be an arithmetic overflow and

// the bag will fail.

IntArrayBag answer = new IntArrayBag(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;

}

public boolean equals(Object obj) // Method returns true if obj is a bag and it has the same number of every element

{ // as the bag that activates the method

if (obj instanceof IntArrayBag) // obj is referring to a location 'IntArrayBag'

{

IntArrayBag candidate = (IntArrayBag) obj; //Typecast being implemented because thinks of 'obj' as a bare object

//Pouring obj into a casting mold that creates a location object

if(candidate.manyItems != this.manyItems)

return false;

for (int i=0; i

if(this.countOccurrences(data[i]) != candidate.countOccurrences(data[i]))

return false;

return true;

}

else

return false; //obj does not refer to a valid IntArrayBag

}

public String toString() // String representation of an object

{

String bag = "";

for (int i=0; i

bag += data[i] + ((i==manyItems - 1)?"":",");

return "{" + bag + "}";

}

public boolean removeAll(IntArrayBag removed)

{

int oldManyItems = this.manyItems;

for (int i=0; i

this.remove(removed.data[i]);

return oldManyItems == this.manyItems;

}

public static IntArrayBag intersection(IntArrayBag b1, IntArrayBag b2)

{

IntArrayBag inter = new IntArrayBag();

if(b1==null && b2==null) inter=null;

else if(b1==null)inter=null;

else if(b2==null)inter.addAll(b1);

else

{

inter.addAll(b1);

for(int i=0; i

inter.remove(b2.data[i]);

}

return inter;

}

}

------------------------------------------------------------------------------

// Luis Terrazas // February 23, 2016 // CS272-M02

import java.applet.Applet; import java.awt.*; // Imports Button, Canvas, TextArea, TextField import java.awt.event.*; // Imports ActionEvent, ActionListener

public class BagApplet extends Applet { // An IntArrayBag for this Applet to manipulate: private IntArrayBag b1 = new IntArrayBag( ); private IntArrayBag b2 = new IntArrayBag( );

// These are the interactive Components that will appear in the Applet. // We declare one Button for each IntArrayBag method that we want to be able to // test. If the method has an argument, then there is also a TextField // where the user can enter the value of the argument. // At the bottom, there is a TextArea to write messages. private Button b1AddButton = new Button("b1.add( )"); private Button b1RemoveButton = new Button("b1.remove( )"); private Button b2AddButton = new Button("b2.add( )"); private Button b2RemoveButton = new Button("b2.remove( )"); private Button b1StringButton = new Button("b1.toString( )"); private Button b2StringButton = new Button("b2.toString( )"); private Button b1RemoveAllButton = new Button("b1.removeAll(b2)"); private Button b2RemoveAllButton = new Button("b2.removeAll(b1)"); private Button b1EqualsButton = new Button("b1.equals(b2)"); private Button intersectionButton = new Button("Intersection(b1, b2 )"); private TextField elementText = new TextField(10); private TextArea feedback = new TextArea(7, 60);

public void init( ) { // Some messages for the top of the Applet: add(new Label("This Test Program has created two bags: b1 and b2. Press Buttons to activate methods.")); addHorizontalLine(Color.blue); // The Button for adding to bag 1: add(b1AddButton); // The Button for removing from bag 1: add(b1RemoveButton); // Textfield for user input add(elementText); // The Button for adding to bag 2: add(b2AddButton); // The Button for removing from bag 2; add(b2RemoveButton); addNewLine(); // The Button will convert bag 1 to string: add(b1StringButton); // The Button will convert bag 2 to string: add(b2StringButton); addNewLine(); // The Button will remove all from bag 2: add(b1RemoveAllButton); // The Button will remove all from bag 1: add(b2RemoveAllButton); addNewLine(); // The Button will equal bag 2 to bag 1: add(b1EqualsButton); addNewLine(); // The Button will intersect bag 1 and bag 2: add(intersectionButton); addNewLine( );

// A TextArea at the bottom to write messages: addHorizontalLine(Color.blue); addNewLine( ); feedback.setEditable(false); feedback.append("I am ready for your first action. "); add(feedback); // Tell the Buttons what they should do when they are clicked: b1AddButton.addActionListener(new b1AListener( )); b1RemoveButton.addActionListener(new b1RListener( )); b2AddButton.addActionListener(new b2AListener()); b2RemoveButton.addActionListener(new b2RListener()); b1StringButton.addActionListener(new b1SListener()); b2StringButton.addActionListener(new b2SListener()); //b1RemoveAllButton.addActionListener(new b1RAListener()); //b2RemoveAllButton.addActionListener(new b2RAListener()); //b1EqualsButton.addActionListener(new b1EListener()); //intersectionButton.addActionListener(new iListener()); } class b1AListener implements ActionListener { public void actionPerformed(ActionEvent event) { try { String userInput = elementText.getText( ); int element = Integer.parseInt(userInput); b1.add(element); feedback.append(element + " has been added to bag 1. "); } catch (NumberFormatException e) { feedback.append("Type an integer before clicking button. "); elementText.requestFocus( ); elementText.selectAll( ); } } } class b1RListener implements ActionListener { public void actionPerformed(ActionEvent event) { boolean b1Input; try { String userInput = elementText.getText( ); int element = Integer.parseInt(userInput); b1Input = b1.remove(element); if(b1Input) feedback.append(element + " has been removed from bag 1. "); else feedback.append(element + " was not in bag 1. "); } catch (NumberFormatException e) { feedback.append("Type an integer before clicking button. "); elementText.requestFocus( ); elementText.selectAll( ); } } }

class b2AListener implements ActionListener { public void actionPerformed(ActionEvent event) { try { String userInput = elementText.getText( ); int element = Integer.parseInt(userInput); b2.add(element); feedback.append(element + " has been added to bag 2. "); } catch (NumberFormatException e) { feedback.append("Type an integer before clicking button. "); elementText.requestFocus( ); elementText.selectAll( ); } } } class b2RListener implements ActionListener { public void actionPerformed(ActionEvent event) { boolean b2Input; try { String userInput = elementText.getText( ); int element = Integer.parseInt(userInput); b2Input = b2.remove(element); if(b2Input) feedback.append(element + " has been removed from bag 2. "); else feedback.append(element + " was not in bag 2. "); } catch (NumberFormatException e) { feedback.append("Type an integer before clicking button. "); elementText.requestFocus( ); elementText.selectAll( ); } } } class b1SListener implements ActionListener { public void actionPerformed(ActionEvent event) { feedback.append("Bag 1: " + b1.toString() + ". "); } } class b2SListener implements ActionListener { public void actionPerformed(ActionEvent event) { feedback.append("Bag 2: " + b2.toString() + ". "); } } class b1RAListener implements ActionListener { public void actionPerformed(ActionEvent event) { boolean b2Input; try { String userInput = elementText.getText( ); int element = Integer.parseInt(userInput); b2Input = b2.removeAll(element); if(b2Input) feedback.append(element + " has been removed from bag 2. "); else feedback.append(element + " was not in bag 2. "); } catch (NumberFormatException e) { feedback.append("Type an integer before clicking button. "); elementText.requestFocus( ); elementText.selectAll( ); } } } } }

private void addHorizontalLine(Color c) { // Add a Canvas 10000 pixels wide but only 1 pixel high, which acts as // a horizontal line to separate one group of components from the next. Canvas line = new Canvas( ); line.setSize(10000,1); line.setBackground(c); add(line); }

private void addNewLine( ) { // Add a horizontal line in the background color. The line itself is // invisible, but it serves to force the next Component onto a new line. addHorizontalLine(getBackground( )); }

}

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

Logidata+ Deductive Databases With Complex Objects Lncs 701

Authors: Paolo Atzeni

1st Edition

354056974X, 978-3540569749

More Books

Students also viewed these Databases questions

Question

How do tariffs and quotas protect a countrys own industries?

Answered: 1 week ago

Question

2. Identify conflict triggers in yourself and others

Answered: 1 week ago