我無法使索引小於arrayList的大小,以至於我可以處理卡片。這裏是我的代碼:如何獲得小於
import java.util.Collection;
import java.util.Collections;
import java.util.Random;
import java.util.ArrayList;
public class Deck {
ArrayList<Card> unusedCards = new ArrayList<Card>();
ArrayList<Card> usedCards = new ArrayList<Card>();
Card newCard = new Card();
Random rand = new Random();
//Creates a Deck of 52 randomly ordered card objects (No repeats)
public Deck() {
for (int i = 0; i <= 52; i++) {
while (unusedCards.contains(newCard)) {
newCard = new Card();
}
unusedCards.add(newCard);
}
}
//shuffles the arraylist of the deck of cards, making it so the cards are dealt in a different order
public void shuffle(){
Collections.shuffle(unusedCards);
}
//Boolean is true when the Unsed deck has no cards left
public boolean isEmpty(){
if (unusedCards.size() == 0) return true;
else return false;
}
//returns an arraylist containing the specified number of cards
public ArrayList<Card> Deal(int numToDeal){
ArrayList<Card> DealCards = new ArrayList<Card>();
for (int i = 0; i < numToDeal; i++){
int index = rand.nextInt(50);
DealCards.add(unusedCards.get(index));
usedCards.add(unusedCards.get(index));
unusedCards.remove(unusedCards.get(index));
}
return DealCards;
}
}
我不斷收到這個錯誤,當我試圖解決一些卡:
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 48, Size: 48
at java.util.ArrayList.rangeCheck(Unknown Source)
at java.util.ArrayList.get(Unknown Source)
at nnajiO.Deck.Deal(Deck.java:41)
at nnajiO.CrazyEights.main(CrazyEights.java:26)
感謝如果你可以提供幫助。