gpt4 book ai didi

java - ArrayBag的grab()和remove()方法,使用.grab()方法后如何删除String?

转载 作者:太空宇宙 更新时间:2023-11-04 13:15:37 25 4
gpt4 key购买 nike

假设我想向 ArrayBag 添加 3 个形容词,并且通过使用 ArrayBag 的 JavaDoc 中的每个方法,如果grab() 方法从 ArrayBag 中随机获取一个形容词并使用它,我应该如何在使用后一次删除一个形容词?

/**
* 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];
}

/**
* 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;
}
}

我已经尝试过的当前代码。

    printText(3, "adjectives");
adjectives.ensureCapacity(3);
adjective = input.nextLine();
String[] arr = adjective.split(" ");
for(String ss : arr) {
adjectives.add(ss);

一旦我调用adjectives.grab(),我该如何删除使用过的随机字符串?非常感谢任何帮助。

最佳答案

答案在于在grab()方法中从ArrayBag中删除元素后更改ArrayBag的大小。

/**
* 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
}

关于java - ArrayBag的grab()和remove()方法,使用.grab()方法后如何删除String?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33560389/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com