【发布时间】:2017-10-02 08:06:29
【问题描述】:
抱歉,如果这是重复的,但我查看了很多答案,但似乎没有一个适用(例如,我的 for 循环从 0 开始,而不是一个常见的错误)。这是字谜文字游戏中使用的一种方法。请帮助我,我已经连续五个小时了,我想我是因为睡眠不足而产生了幻觉。
编辑:错误发生在ugh.remove(thing.charAt(i));这一行
public boolean anagramOfLetterSubset(String thing, ArrayList<Character> reference) {
ArrayList<Character> ugh = new ArrayList<Character>();
for (int h = 0; h < reference.size(); h++) {
ugh.add(reference.get(h));
}
for (int i = 0; i < thing.length(); i++) { //cycles through the letters in the word
for (int f = 0; f < reference.size(); f++) { //cycles through the characters in the reference arraylist
if ((reference.get(f) == thing.charAt(i)) && (reference.indexOf(thing.charAt(i)) != -1)) { //sees if the letter and the character match
ugh.remove(thing.charAt(i)); //removes first instance of character
}
}
}
if (ugh == reference)
return false; // change the value returned
else
return true;
}
【问题讨论】:
-
请添加堆栈跟踪。
-
请注意,
ugh == reference永远不会为真,因为它们是不同的对象实例。 -
thing.charAt(i);可以返回比ugh中的元素数更大的索引 -
我相信
remove(thing.charAt(i))会调用remove(int)而不是remove(Object)。请改用remove((Character) thing.charAt(i))。 -
正如@khelwood 所指出的,这将扩大到
int
标签: java arraylist indexoutofboundsexception