Solved

Java: How to build objects inside a while loop

Posted on 2011-09-03
16
300 Views
Last Modified: 2012-05-12
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
Comment
Question by:InfoTechEE
  • 10
  • 5
16 Comments
 
LVL 47

Expert Comment

by:for_yan
Comment Utility
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
 
LVL 47

Expert Comment

by:for_yan
Comment Utility
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
 
LVL 47

Expert Comment

by:for_yan
Comment Utility
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
 

Author Comment

by:InfoTechEE
Comment Utility
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
 
LVL 22

Expert Comment

by:pivar
Comment Utility
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
 

Author Comment

by:InfoTechEE
Comment Utility
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
 
LVL 47

Expert Comment

by:for_yan
Comment Utility
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
 

Author Comment

by:InfoTechEE
Comment Utility
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
What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 
LVL 47

Expert Comment

by:for_yan
Comment Utility
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
 

Author Comment

by:InfoTechEE
Comment Utility
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
 

Author Comment

by:InfoTechEE
Comment Utility
Dang...OK. I was specifically told to use ArrayLists.
0
 
LVL 47

Expert Comment

by:for_yan
Comment Utility
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
 
LVL 47

Expert Comment

by:for_yan
Comment Utility
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
 
LVL 47

Expert Comment

by:for_yan
Comment Utility


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
 
LVL 47

Accepted Solution

by:
for_yan earned 500 total points
Comment Utility

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
 
LVL 47

Expert Comment

by:for_yan
Comment Utility
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

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

For customizing the look of your lightweight component and making it look lucid like it was made of glass. Or: how to make your component more Apple-ish ;) This tip assumes your component to be of rectangular shape and completely opaque. (COD…
By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:

743 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now