Search code examples
javalistobject

Not adding to list while looping in Java


I'm learning Java and I'm making an easy cards game. The first thing I want to do y to create the deck. I'm having a problem with creating and adding objects to a List of the objects while looping.

First of all, I made a class "Card". The constructor is:

public CartaEspana(int num, int palo) {
        this.numero = num;
        this.palo = palo;
    }

Then I made a deck class with this constructor

        //atributos
    private int id;
    private List<CartaEspana> baraja= new ArrayList();
    //Propiedades
    public int getId() {
        return id;
    }
    public List<CartaEspana> getJuegoCartas() {
        return baraja;
    }
    public void setId(int id) {
        this.id = id;
    }
    public void setJuegoCartas(List<CartaEspana> juegoCartas) {
        this.baraja = juegoCartas;
    }
    public void addCarta(CartaEspana carta) {
        this.baraja.add(carta);
    }
    public BarajaEspanola(int id) {
        this.id = id;
        int i = 0, j = 0;
        for(i = 0; i == 3; i++) {
            for(j = 1; j == 12; j++) {
                
                this.addCarta(new CartaEspana(j,i));
            }
        }
    }

When I create the deck and ask for the list lenght it says that lenght is 0; I've tried

    public BarajaEspanola(int id) {
        this.id = id;
        this.addCarta(new CartaEspana(1,0));
        this.addCarta(new CartaEspana(2,0));

        }
    }

and lenght now is two. Which is the difference and why the loop does not create the objects inside de Deck? Thanks


Solution

  • The two nested loops are executed zero times.

    Change the == to <=. We want to ask on each loop “is i less than or equal to the limit of three” and “is j less than or equal to the limit of twelve”.

    for(i = 0; i <= 3; i++) {
        for(j = 1; j <= 12; j++) {
           ...
        }
    }