ArrayList:remove方法抛出java.lang.IndexOutOfBoundException
我目前在AP CS elevens实验室工作,该实验室让您开发自己的卡牌和牌组类,以模拟卡牌游戏。我目前正在编写一个洗牌方法,它接受一个ArrayList:remove方法抛出java.lang.IndexOutOfBoundException,java,methods,arraylist,Java,Methods,Arraylist,我目前在AP CS elevens实验室工作,该实验室让您开发自己的卡牌和牌组类,以模拟卡牌游戏。我目前正在编写一个洗牌方法,它接受一个牌组对象并随机洗牌其中的牌对象。以下是我目前的方法: public void shuffle() { ArrayList<Card>copy = new ArrayList <Card> (); for (int i = cards.size(); i >= 0; i--) { int d = (int)(Math.ran
牌组
对象并随机洗牌其中的牌
对象。以下是我目前的方法:
public void shuffle() {
ArrayList<Card>copy = new ArrayList <Card> ();
for (int i = cards.size(); i >= 0; i--) {
int d = (int)(Math.random()*i);
copy.add(cards.get(d));
cards.remove(d);
}
size = cards.size();
cards = copy;
}
看看你的代码
for (int i = cards.size(); i >= 0; i--) {
当大小为0时(没有卡时),这将进入循环,因此出现java.lang.IndexOutOfBoundsException
将循环条件中的>=0
更改为>0
for (int i = cards.size(); i > 0; i--) {
请注意,
集合
已经有了一种方法,它将列表
作为参数。当没有剩余卡片时(即cards.size()==0
尝试移除卡片。通过将循环终止条件更改为i>0
来修复它
或者,我可能会以不同的方式编写循环:
while (!cards.isEmpty()) {
int d = (int) (Math.random() * cards.size());
copy.add(cards.remove(d));
}
这对我来说似乎更清楚了。当出现问题行时,会出现什么问题?程序会编译,但一旦运行,我就会得到一个
java.lang.IndexOutOfBoundsException:Index:0,Size:0
错误。如果这一行没有出现,它运行正常请注意,还有java.util.Collections.shuffle()
,这将完成这项工作。我提到它只是作为一个评论,因为我认为自己实现shuffle是这个练习的一部分。
while (!cards.isEmpty()) {
int d = (int) (Math.random() * cards.size());
copy.add(cards.remove(d));
}