我在编写的包含ArrayList
的课程时遇到了问题。
代码:
import java.util.ArrayList;
public class AscendingPile {
public ArrayList<Integer> pile = new ArrayList<Integer>() {{
add(1);
}};
public void lay(int card) throws IllegalArgumentException{
int lastCard = pile.get(pile.size() - 1);
if(card > lastCard || card == lastCard - 10){
pile.add(card);
}
else {
throw new IllegalArgumentException("....");
}
}
// returns last card on the deck
public int getCard() {
return pile.get(pile.size() - 1);
}
}
问题是lay
方法:我没有定义一个新的局部变量,而是希望if语句看起来像这样:
if(card > pile.getCard() || card == pile.getCard() - 10)
但IntelliJ表示无法解析符号getCard()
如何更改代码以获得所需的结果?
答案 0 :(得分:1)
但IntelliJ表示无法解析符号getCard()
确实如此,ArrayList类没有名为 getCard()的方法
而不是:
from copy import deepcopy
discarded_overlapped = []
def overlap(overlapped,discarded):
if all(x is None for x in overlapped):
discarded.sort()
if discarded not in discarded_overlapped:
discarded_overlapped.append(discarded)
return
for i in range(len(overlapped)):
if not overlapped[i] == None:
overlapped_copy = deepcopy(overlapped)
discarded_copy = deepcopy(discarded)
for j in overlapped[i]:
if j not in discarded:
discarded_copy.append(j)
overlapped_copy[j] = None
overlapped_copy[i] = None
overlap(overlapped_copy,discarded_copy)
Data = [None,[2,3,4],[1],[1],[1,5],[4,6],[5],None,None]
overlap(Data,[])
print(discarded_overlapped)
# [[2, 3, 4, 6], [2, 3, 4, 5], [1, 5], [1, 4, 6]]
直接调用类 AscendingPile
的方法pile.getCard();
答案 1 :(得分:0)
如前所述,只需直接调用getCard()。
我目前也正在编写纸牌游戏。我强烈建议您使用Stack而不是使用ArrayList作为套牌。 (见文件https://docs.oracle.com/javase/7/docs/api/java/util/Stack.html)。
Stack为您提供了有用的方法,如pop()和push()。
Pop删除堆栈顶部的对象,就像你现在使用getCard()方法一样。