gpt4 book ai didi

java - 从哈希集中删除项目

转载 作者:行者123 更新时间:2023-12-03 02:23:36 25 4
gpt4 key购买 nike

我正在创建一个问答游戏。有些答案有替代答案,例如:

俄罗斯总统是谁?

  • Vladimir Poetin
  • Poetin

这是代码:

for (HashSet<String> answer : answers) {
for (String alternative : answer) {
// Apply levensthein
int distance = levensthein(givenAnswer, alternative);
double ratio = ((double) distance) / (Math.max(alternative.length(), givenAnswer.length()));
// 20 % error margin
if (ratio <= 0.2) {
// remove this set of answers, so you can't try in the same answer again
answers.remove(answer);
return true;
}
}
}

在 levensthein 检查之后,必须将答案从 Hashset 中删除。它适用于问题没有替代答案的情况。

我怎样才能让它工作?有什么想法我做错了吗?

谢谢!

最佳答案

增强的 for 循环不适合从正在迭代的集合中删除元素。请改用显式迭代器。

Iterator<HashSet<String>> aIter = answers.iterator();
while (aIter.hasNext()) {
HashSet<String> answer = aIter.next();
Iterator<String> iter = answer.iterator();
while (iter.hasNext()) {
String alternative = iter.next();
// Apply levensthein
int distance = levensthein(givenAnswer, alternative);
double ratio = ((double) distance) / (Math.max(alternative.length(), givenAnswer.length()));
// 20 % error margin
if (ratio <= 0.2) {
// remove this set of answers, so you can't try in the same answer again
aIter.remove();
return true;
}
}
}

关于java - 从哈希集中删除项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34451676/

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