Issue
Say I want to add 3 adjectives to an ArrayBag, and by using every method in the JavaDoc for ArrayBag, what should I do to remove an adjective one at a time after use if the grab() method takes an adjective at random from the ArrayBag and uses it?
/**
* Accessor method to retrieve a random element from this ArrayBag and will
* remove the grabbed element from the ArrayBag
*
* @return A randomly selected element from this ArrayBag
* @throws java.lang.IllegalStateException Indicated that the ArrayBag is
* empty
*/
public E grab() {
int i;
//E n;
if (items == 0) {
throw new IllegalStateException("ArrayBag size is empty");
}
i = (int) (Math.random() * items + 1);
// n = elementArray[i - 1];
//if (items != 0) {
// remove(n);
//}
return elementArray[i - 1];
}
and
/**
* Remove one specified element from this ArrayBag
*
* @param target The element to remove from this ArrayBag
* @return True if the element was removed from this ArrayBag; false
* otherwise
*/
public boolean remove(E target) {
int i;
if (target == null) {
i = 0;
while ((i < items) && (elementArray[i] != null)) {
i++;
}
} else {
i = 0;
while ((i < items) && (!target.equals(elementArray[i]))) {
i++;
}
}
if (i == items) {
return false;
} else {
items--;
elementArray[i] = elementArray[items];
elementArray[items] = null;
return true;
}
}
My current code I have tried.
printText(3, "adjectives");
adjectives.ensureCapacity(3);
adjective = input.nextLine();
String[] arr = adjective.split(" ");
for(String ss : arr) {
adjectives.add(ss);
Once I call adjectives.grab()
how do I go about removing that random String once it has been used? Any help is much appreciated.
Solution
The answer lies within changing the size of the ArrayBag after removing the element from the ArrayBag all within the grab() method.
/**
* Accessor method to retrieve a random element from this ArrayBag and will
* remove the grabbed element from the ArrayBag
*
* @return A randomly selected element from this ArrayBag
* @throws java.lang.IllegalStateException Indicated that the ArrayBag is
* empty
*/
public E grab() {
int i;
E n;
if (items == 0) {
throw new IllegalStateException("ArrayBag size is empty");
}
i = (int) (Math.random() * items + 1);
n = elementArray[i - 1];
remove(n);
trimToSize();
return n
}
Answered By - KrakenJaws
Answer Checked By - Clifford M. (JavaFixing Volunteer)