• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 322
  • Last Modified:

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?
0
InfoTechEE
Asked:
InfoTechEE
  • 10
  • 5
1 Solution
 
for_yanCommented:
Sure it makes sense - yiu first craete an array before the loop and then create invidual eleentts inside the loop as you suggeated it
0
 
for_yanCommented:
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];
0
 
for_yanCommented:
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
0
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
InfoTechEEAuthor Commented:
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?
0
 
pivarCommented:
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
0
 
InfoTechEEAuthor Commented:
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?
0
 
for_yanCommented:
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
0
 
InfoTechEEAuthor Commented:
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.
0
 
for_yanCommented:
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
0
 
InfoTechEEAuthor Commented:
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?
0
 
InfoTechEEAuthor Commented:
Dang...OK. I was specifically told to use ArrayLists.
0
 
for_yanCommented:
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
0
 
for_yanCommented:
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
0
 
for_yanCommented:


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

0
 
for_yanCommented:

Objects inside teh ArrayList do not have any name

when you say
ArrayList<Card> ar = new ArrayList<Card>();
Card cd = new Card(something);
ar.add(cd);

"cd" here is not any name - it was a te[porarily variable which held address
to the object which you create; next time you craete a new object of the same type
the address will be different though in your code it will still be named "cd"

When your objects get populated into the ArrayList, this arraylist maintains
the array of addresses and each address pints to the object of type Card
ArrayList has no idea of the name for the object, hoever it has all of them ordered in certain
order and you reach out to them mentioniong the oeder number of particular
obejct.

So when I say

Card cd1 = ar.get(5);

then java will provide the address of the object number 5 in the arraylist (they alwys start counting from zero in java of cores)
and populate variable cd1 with this address.

After that you can use this address to invole methods of my card object,
such as cd1.getSuite() - which will return the suite of the card or
cd1.getRank() - which will return rank
and in your Card class you can define method
say boolean equalCard(Card c)
which will return true if both suite and rank of card c
match to your card on which thsi method is invoked.
In this way you would know that the cards are the same.

You can define a method
String toString()
which will return your string representation of the card, say like "2c"
and then you may compare cards using their toString() methods -
all those are different options and for design of each game/program you amy chose those you'd
 prefer taking into account how your cards are used in the game.

Let me know if  there is something you don't understand about the ArrayList - it is very
important collection and you want to use it in lots of Java propgramming

look through API for ArrayList - tht;s were you find all those add() and get() methods metioned above with explanation
http://download.oracle.com/javase/6/docs/api/java/util/ArrayList.html








0
 
for_yanCommented:
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

0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

  • 10
  • 5
Tackle projects and never again get stuck behind a technical roadblock.
Join Now