Write a function that removes a String from the StringBag (if it is in the Strin
ID: 3912936 • Letter: W
Question
Write a function that removes a String from the StringBag (if it is in the StringBag). It should do this by finding the index where the String exists, and then overwriting it with the element at the last position. The last element should then be dropped from the bag. If an element is removed, return true, otherwise return false.
Write your test case for this method.
public void testRemove()
// Replace this test with your code
Write your method.
public boolean remove(String item)
{
// Replace this test with your code
}
public void testRemove()
// Replace this test with your code
Explanation / Answer
//StringBag.java
class StringBag
{
String []bag;
int size;
//constructor
public StringBag(int size)
{
//allocate memory for string bag for number of elements indicated by size
bag=new String[size];
size = 0;
}
void insert_into_bag(String item)
{
bag[size++]=item;
}
void print()
{
for(int i = 0; i < size;i++)
{
System.out.printf("%d: %s ",i+1,bag[i]);
}
System.out.println(" ");
}
public boolean remove(String item)
{
for(int i = 0; i < size;i++)
{
if(bag[i] == item )
{
//overwrite with last element and
bag[i]=bag[size-1];
bag[size-1]= null;
--size;
return true;
}
}
return false;
}
}
----------------------------------------------------------
//Main.java with testRemove() function
public class Main
{
public static void testRemove()
{
//System.out.println("Hello World");
StringBag mybag=new StringBag(5);
//add items into mybag
System.out.println("Bag contains: ");
mybag.insert_into_bag("John");
mybag.insert_into_bag("Mary");
mybag.insert_into_bag("Smith");
mybag.insert_into_bag("Ronald");
mybag.insert_into_bag("Stephan");
mybag.print();
if( mybag.remove("John") == true)
{
System.out.println("John has been removed from bag ");
}
else
System.out.println("Item is not present in bag ");
System.out.println("Bag after remove of an item ");
mybag.print();
}
public static void main(String[] args) {
testRemove();
}
}
//to see different output change the string value passde to remove function in testRemove function
-----------------------------------------------------------------------
//output1
Bag contains:
1: John
2: Mary
3: Smith
4: Ronald
5: Stephan
Item is not present in bag
Bag after remove of an item
1: John
2: Mary
3: Smith
4: Ronald
5: Stephan
-----------------------------------------------------
//ouput2
Bag contains:
1: John
2: Mary
3: Smith
4: Ronald
5: Stephan
John has been removed from bag
Bag after remove of an item
1: Stephan
2: Mary
3: Smith
4: Ronald
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.