emmynaki emmynaki - 1 month ago 15
Java Question

game of cards in java array and arraylist

So basically I'm making a game of cards and I'm trying to remove a certainAmount of cards off from the top of my deck and then return that certainAmount as an array of size certainAmount and I can't figure out why my logic is incorrect

private ArrayList<Card> cards;

public Deck() {
cards = new ArrayList <Card>();

for (int type= 0; type<=4; type++){
for (int value=1; value<=9; value++){
Card newCard = new Card (value, type);


public Deck(Deck other) {
cards = new ArrayList<Card> (other.cards);

public Card getCardAt(int position) {
Card gottenCard = cards.get(position);
return gottenCard;

public int getNumCards() {
int sizeOfArrayList = cards.size();
return sizeOfArrayList;

//remove certain amount (numCards) of cards from top of arraylist
public Card[] deal(int numCards) {
Card[] newArray = new Card[numCards];

//assigning removed card to new array positions
for (int newArrayPosition=0; j<newArrayPosition;newArrayPosition++) {
newArray[j] = cards.remove((cards.size()-1));
for (int newArrayPosition=0; j<newArrayPosition;newArrayPosition++) {
newArray[j] = cards.remove((cards.size()-1));
return newArray;


So what I have understood from your question, I believe I have an answer that can help you. I think the use of ArrayList's are imperative in this situation. ArrayList's allow for easy removal and addition of values without needing to worry about 'nullPointerExceptions.' Therefore, my answer uses ArrayList's that contains integers that represent cards. In your scenario, just replace 'Card' with 'Integer' in the ArrayList's Generic Parameter. My code:

import java.util.ArrayList;

public class Answers {

     public static void main(String[] args) {
         Answers main = new Answers();
         // Original Deck
         ArrayList<Integer> cards = new ArrayList<Integer>();

         // Add to original deck

         System.out.println("Removed Cards Deck: " + main.deal(3, cards));
             // Removed Cards Deck: [1, 2, 3]

          System.out.println("Original Deck: " + cards); 
             // Original Deck: [-1, -1, -1, 4, 5]

     public ArrayList<Integer> deal(int numCards, ArrayList<Integer> deckOfCards) { 
          // Deck that will contain the removed cards
          ArrayList<Integer> newCardsArray = new ArrayList<Integer>();

          for (int i = 0; i < numCards; i++) { 
                    // Add to remove cards deck

               deckOfCards.set(i, -1); 
                    // Set taken cards in original deck to '-1'
          return newCardsArray;


Hope this helps!