问题描述
public boolean isTwoPair() {
boolean isTwoPair = false;
Collections.sort(deck);
List<Card> cards = new LinkedList<Card>(deck);
System.out.println(cards);
for (int i = 0; i < cards.size()-1; i++) {
for (int j = i + 1; j < cards.size()-1; j++) {
if (deck.get(i).equals(deck.get(j))) {
cards.remove(i);
cards.remove(j);
System.out.println(cards);
}
}
}
return isTwoPair;
}
我认为我的问题出在我的cards.remove().当我删除卡时,下次将其删除时,会将其从更改后的列表中删除.有两种方法可以从列表中删除索引号相同的两个项目?
I think my problem is with my cards.remove(). When I remove a card, the next time the card is removed it removes it from an altered list. Is there a way to remove two items from a list while they have the same index numbers?
如果我必须删除索引0,1,因为它们都是像这样的对:
If I have to remove index 0,1 because they are both pairs like so:
[Ace,Ace,Three,Four,Four]
此代码将其删除(删除索引0)
the code removes it like this(removing index 0)
[Ace,Three,Four,Four]
而不是从第一个列表中删除索引1(Ace),而不是从第二个列表中删除索引,因此
than instead of removing the index 1(Ace) from the first list it removes it from the second list so
[Ace,Four,Four]
它从第二个列表(三个)中删除了索引1.
It removed the index 1 from the second list which was three.
这就是我所期望的
[Three,Four,Four]
目前,我希望我的循环能够拾取并删除四"和四"
At this point I expect my loop to pick up and remove Four and Four
public boolean isTwoPair() {
boolean isTwoPair = false;
Collections.sort(deck);
List<Card> cards = new LinkedList<Card>(deck);
System.out.println(cards);
for (int cardOne = 0; cardOne < cards.size(); cardOne++) {
for (int cardTwo = cardOne + 1; cardTwo < cards.size(); cardTwo++) {
if (deck.get(cardOne).equals(deck.get(cardTwo))) {
cards.remove(cardOne);
cards.remove(cardTwo-1);
System.out.println(cards);
for(int cardThree = 0; cardThree < cards.size(); cardThree++){
for(int cardFour = cardThree+1; cardFour < cards.size(); cardFour++){
if(cards.get(cardThree).equals(cards.get(cardFour))){
cards.remove(cardThree);
cards.remove(cardFour-1);
System.out.println(cards);
isTwoPair = true;
}
}
}
}
}
}
return isTwoPair;
}
这就是我现在正在使用的,如果没有必要,我真的不想创建一个新变量,所以我决定不删除对象
this is what I am using now, I didn't really want to make a new variable if I didn't have to so I decided to not remove Object
推荐答案
如果您知道j
始终大于i
(由于for循环),则如果先删除索引为i
的元素,则您可以删除索引为j - 1
的元素,以得到预期的结果.
If you know j
is always greater than i
(because of the for loop), if you delete the element with index i
first then you can delete the element with index j - 1
getting the expected result.
cards.remove(i);
cards.remove(j-1);
这篇关于在遍历列表时按索引从列表中删除项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!