Search code examples
javaarraylistmethods

Why is my ArrayList returning no elements when I try to add some inside a method?


For some reason, when I try to add new elements to an ArrayList called "deck" using a method, it doesn't return anything. I am trying to have an entire ArrayList have what you would typically see in a standard card deck.

Code:

public class PokerTHEMain {
    // Objects

    private String[] cardTypes = {"Spades", "Hearts", "Clubs", "Diamonds"} ;
    private String[] cardValues = {"Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King"} ;
    private ArrayList<String> deck = new ArrayList<String>();

    // Methods

    void ResetDeck() {
        this.deck.clear() ;

        for (int cardTypesItem = 0 ; cardTypesItem < this.cardTypes.length ; cardTypesItem++) {
            for (int cardValuesItem = 0 ; cardValuesItem < this.cardValues.length ; cardValuesItem++) {
                this.deck.add(this.cardValues[cardValuesItem] + " of " + this.cardTypes[cardTypesItem]) ;
            }
        }
    }
...

What I use to check for values (inside of the main method):

for (int i = 0 ; i < PokerTHEMain.deck.size() ; i++) {
            out.println(PokerTHEMain.deck.get(i)) ;
}

For some more information, I am using IntelliJ IDEA as my IDE.


Solution

  • My guess is that you havent created a main method. In my example , in the main method I create a new PokerTHEMain Object and Reset the deck , then print it

    package org.example;
    
    import java.util.ArrayList;
    
    public class PokerTHEMain {
    // Objects
    
     private String[] cardTypes = {"Spades", "Hearts", "Clubs", "Diamonds"};
     private String[] cardValues = {"Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King"};
     private ArrayList<String> deck = new ArrayList<String>();
    
    // Methods
    
    void ResetDeck() {
        this.deck.clear();
        for (int cardTypesItem = 0; cardTypesItem < this.cardTypes.length; cardTypesItem++) {
            for (int cardValuesItem = 0; cardValuesItem < this.cardValues.length; cardValuesItem++) {
                this.deck.add(this.cardValues[cardValuesItem] + " of " + this.cardTypes[cardTypesItem]);
            }
        }
    }
    
    public static void main(String[] args) {
        PokerTHEMain pokerTHEMain = new PokerTHEMain();
        pokerTHEMain.ResetDeck();
        System.out.println(pokerTHEMain.deck);
    }}
    

    Console output :
    enter image description here

    Hope you find this helpfull!!!