Hi again, I posted last week about a Go Fish game that I was trying to write - well I've sorted out my past issues and now I'm trying to rewrite my CardPile class (that defines such things as the deck or a player's hand) to consist of an ArrayList of Card objects, rather than an Array. I've gotten the class to compile and I'm getting a runtime error that I think traces back to the searchValue method of the following class:
import java.util.Random;
import java.util.List;
import java.util.ArrayList;
public class CardPile {
private ArrayList<Card> cards = new ArrayList<Card>();
private static Random r = new Random(1);
public void addToBottom(Card c) {
if (cards.size() == 52) {
System.out.println("The CardPile is full. You cannot add any more Card objects.");
}
this.cards.add(c);
}
public Card removeCard(Card c) {
if (this.cards.contains(c)) {
this.cards.remove(c);
}
return null;
}
public Card removeTop() {
return this.cards.remove(0);
}
public int searchValue(int value) {
int count = 0;
//I know there is an ArrayList method that gives me the first/last
//indices of a specified Object, but we're just looking for the value-
//aspect of the Card, not the suit, so I decided to stick with the old logic
for (int i = 0;i < cards.size();i++) {
if (this.cards.get(i).getValue() == value) {
count++;
}
}
return count;
}
public Card[] removeAll(int value) {
int count = searchValue(value);
Card[] removed = new Card[count];
for (int i = 0;i < this.cards.size();i++) {
if (this.cards.get(i).getValue() != value) {
this.cards.remove(i);
}
}
this.cards.toArray(removed);
return removed;
}
public int getNumberCards() {
return this.cards.size();
}
public String toString() {
if (this.cards.isEmpty()) {
return "";
}
String builder = "";
for (int i = 0;i < this.cards.size();i++) {
builder = builder + this.cards.get(i) + ", ";
}
builder = builder + this.cards.get(this.cards.size() - 1);
return builder;
}
public void shuffle() {
if (this.cards.isEmpty()) {
return;
}
for (int count = 0; count < 100000;count++) {
int i = r.nextInt(this.cards.size());
int j = r.nextInt(this.cards.size());
Card temp = this.cards.get(i);
this.cards.set(i, this.cards.get(j));
this.cards.set(j, temp);
}
}
public static CardPile makeFullDeck() {
CardPile deck = new CardPile();
for (int suit = 0;suit < 4;suit++) {
for (int value = 1; value < 14;value++) {
deck.addToBottom(new Card(suit, value));
}
}
deck.shuffle();
return deck;
}
}
Any idea what's wrong with that method? I feel like it's a matter of me not fully understanding the properties of an ArrayList, but I really don't know where to start...