0

I am working on a command line type of program that would allow you to play solitaire. I currently have class Deck and class Card. In class Deck i have an ArrayList and two methods - one that creates a deck and one that shuffles it. I need to create a method that deals a card - meaning a method that would pick a random element from an ArrayList and it is gonna erase it from the ArrayList. When a card is dealt it is not in the ArrayList anymore, i believe. Here is the code in my Deck class:

public class Deck {
   private ArrayList deck = new ArrayList < Card > ();
   private Random randomGenerator;

}

public Deck() {
 for (Suit s: Suit.values())
  for (Numbers n: Numbers.values()) {
   Card c1 = new Card(n, s);
   deck.add(c1);
   System.out.println(deck);
  }
}
private void printAll() {}
public void shuffle() {
 Collections.shuffle(deck);
}

I'm really having a hard time with creating a method that would erase the dealt element, what i have done so far is pretty much based on the answers of this problem but it is not quite what i need. Retrieving a random item from ArrayList

public Card deal(deck) {
    Random rand = new Random();
    Card dealtCard = rand.deck();
    return dealtCard;
}

Could anyone provide any guidance for me on this method? Please and thank you

Scary Wombat
  • 44,617
  • 6
  • 35
  • 64

2 Answers2

3

Really the entire point of shuffling the deck is to allow you to deal from the top of the deck and get random cards each time. So if the Deck class has:

private final List<Card> cards = new ArrayList<>();

And you have called Collections.shuffle(cards) then all you need to do to get the top card in the deck is:

public Card deal() {
    return cards.remove(0);
}

You should also have an isEmpty method so that the caller can make sure there are cards left in the deck before calling deal. That's better coding practice than catching the IndexOutOfBoundsException.

sprinter
  • 27,148
  • 6
  • 47
  • 78
  • @CatV — also notice the proper declaration: `List cards = new ArrayList<>();` ... cards is a `List` and the chosen implementation of the List is an `ArrayList` -- but the code shouldn't care about that choice, so you just declare `List` – Stephen P May 10 '18 at 00:53
-1

You could use something like this

Random rand = new Random();

int randomElement = givenList.get(rand.nextInt(givenList.size()));

I think this link might be useful http://www.baeldung.com/java-random-list-element

  • 1
    This does not remove the card, so the same card could be dealt many times. See 2.4 _"Select Random Items Without Repetitions"_ in the article you linked to. – Stephen P May 10 '18 at 00:58