Link to home
Start Free TrialLog in
Avatar of InfoTechEE
InfoTechEE

asked on

Java: How to build objects inside a while loop

I need to create many new objects inside the while loop. All objects must have a different name. Here's my code:

while(counter<cardsArray.length)
   {
        Card exampleObj = new Card(cardsArray[counter], cardsArray[counter+1]);
        counter += 3;
   }

The problem with this code is that it will only create 1 new object called exampleObj.

I would like to create many new objects all with different names as in: exampleObj1, exampleObj2, etc...

Even better would be to create these objects and call them Obj "cardsArray[counter], cardsArray[counter+1]"

Let me know if that last part made any sense?
Avatar of for_yan
for_yan
Flag of United States of America image

Sure it makes sense - yiu first craete an array before the loop and then create invidual eleentts inside the loop as you suggeated it
The only problem with this approach that before the loop you'll have to creeate the array and declare how mmany cards you'll have (at least maximum),
Say
Card [] cardsArray = new Card[100];
What if you don't kniw how many cards you'll have?
For that situation ArrayList is more convenient

You say

ArrayList ar = new ArrayList();

And then inside the loop you say

Card cd = new Card(something);
ar.add(cd);

So inside yiur araylist you'll store all different cards this way althiyu you'll create your card under the same name.

Read API for ArrayList - youkll see useful methiods there and ArrayList is very usefuil objecvt which you can use instead of arrays - very conevnient
Avatar of InfoTechEE
InfoTechEE

ASKER

OK, I'm actually suppose to work with ArrayList of Objects (Cards). I have a regular Char array that I would like to loop through to parse it and get its elements and convert them to objects. Then store these objects in ArrayList.
So here's what I have:
cardsArray is a Char Array which holds : "2c 3s 6d 7s 8h Kh Jd 4d Jc Kc Qc Tc 9c Jh 9s 9h 9d Qs Ks Js"

ArrayList<Card> cardsArrayList = new ArrayList<Card>();
int counter = 0;
while(counter<cardsArray.length)
   {
      Card exampleObj = new Card(cardsArray[counter], cardsArray[counter+1]);
      counter += 3;
  }

I would like to modify the code inside the loop body to do the following:

1. Create a new object out of the array elements. Then insert this object into ArrayList. How did I do that?
Hi,

Better to use an array for the objects:

int i = 0;
 Card exampleObj[] = new Card[cardsArray.length/3+1];
 while(counter<cardsArray.length)
   {
      exampleObj[i++] = new Card(cardsArray[counter], cardsArray[counter+1]);
        counter += 3;
   }

Creating unique names for each instance is not feasible AFAIK. If you need names you could have a nameproperty in the Card object. Or you could use a Map with name as key and the Card instance as value.

/peter
Seems like you're ahead of me :)

I need a way to have the objects (cards) inside the ArrayList to have meaningful names such as King Diamonds (Kd) or 7 hearts (7h).

I have that string I mentioned in my previous post, is there a way to name the object using the elements inside the object?
Just after you create Card object with the constructoir yoiu put

cardsArrayList.add(exampleObj);

And in this way all your objects will be collected in the arrayList
If I don't have names of the objects I'll have 52 objects in the array list without meaningful names. It might get confusing as I will later on need to work and compare these objects to other player's cards.
For thart purpse you rather uise HashMap where you add a pair - key (or name) vs Value (your Objec)
In the arraylist yoiu cannot name elements
for_yan: if I use your approach, i'll just have like 20 objects with the exact same name inside the array list. How will I be able to work with the objects?
Dang...OK. I was specifically told to use ArrayLists.
For this situatin in the object Card you should define the equals() mnethid which should allow yoiu to compare yoiur objects - you don't need names to compare them
You can google say card deck in Java and you'll see many implementaitions of card decks and games in java - some very illustartive
When I get to my computer I can post a couople of very good links


Look at these examples of representing the card deck:
http://www.dreamincode.net/forums/topic/110380-deck-of-cards-using-various-methods/

One of the examples down below is based on the ArrayList.

if you google "Java deck of cards" you'll find all sorts of eaxamples
representing a deck of cards in Java

ASKER CERTIFIED SOLUTION
Avatar of for_yan
for_yan
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
This is an example of some begginning of card game
based on modifies code from the libnk I posted above.
I hope it will give you some initial idea.
This is actually compileing and ecxecuting (see output below)
and using arraylist

package javacards;

import java.util.ArrayList;
import java.util.Random;

public class Card
{
	private int rank, suit;

	private static String[] suits = { "h", "s", "d", "c" };
	private static String[] ranks  = { "A", "2", "3", "4", "5", "6", "7", "8", "9", "T", "J", "Q", "K" };


	Card(int suit, int rank)
	{
		this.rank=rank;
		this.suit=suit;
	}

    Card(String s){
        for(int i=0; i<ranks.length; i++){
            if(s.substring(0,1).equals(ranks[i])){
                this.rank = i;
            }
        }
           for(int i=0; i<suits.length; i++){
            if(s.substring(0,1).equals(suits[i])){
                this.suit = i;
            }
        }


    }

	public @Override String toString()
	{
		  return ranks[rank] +  suits[suit];
	}

	public int getRank() {
		 return rank;
	}

	public int getSuit() {
		return suit;
	}

}

class Hand {

    ArrayList<Card> cards;

    Hand(String s) {

        cards = new ArrayList<Card>();

        String [] cardStrings = s.split("\\s+");
        for(int j=0; j<cardStrings.length; j++){
            cards.add(new Card(cardStrings[j]));

        }

    }

    Hand (ArrayList <Card> cards){
        this.cards = cards;
    }

    public ArrayList getCards(){
        return cards;
    }

    public String toString(){
        String s = "";
        for(Card c : cards){
            s += c.toString() + " ";
        }
        return s;
    }

}
 class Deck {
	private Card[] cards;
	int i;

	Deck()
	{
		i=51;
		cards = new Card[52];
		int x=0;
		for (int a=0; a<=3; a++)
		{
			for (int b=0; b<=12; b++)
			 {
			   cards[x] = new Card(a,b);
			   x++;
			 }
		}
	}

	public Card drawFromDeck()
	{
		Random generator = new Random();
		int index=0;

		index = generator.nextInt( i );

		Card temp = cards[index];
		cards[index]=cards[i];
		cards[i]=null;
		i--;
		return temp;
	}
}

class Play {


    public static void main(String[] args) {
        Deck deck = new Deck();
        ArrayList <Card>cards = new ArrayList<Card>();
        for(int j=0; j<5; j++){
            cards.add(deck.drawFromDeck());
            
        }

        Hand h = new Hand(cards);
        System.out.println(h.toString());

  }

}

Open in new window



Js 4d 9c Kd 3c 

Open in new window