Solved

Java: How to build objects inside a while loop

Posted on 2011-09-03
16
302 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
ID: 36478910
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
ID: 36478913
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
ID: 36478918
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
ID: 36478920
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
ID: 36478928
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
ID: 36478933
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
ID: 36478934
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
ID: 36478941
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
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
LVL 47

Expert Comment

by:for_yan
ID: 36478942
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
ID: 36478944
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
ID: 36478948
Dang...OK. I was specifically told to use ArrayLists.
0
 
LVL 47

Expert Comment

by:for_yan
ID: 36478952
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
ID: 36478956
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
ID: 36479036


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
ID: 36479053

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
ID: 36479206
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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
groupNoAdj 7 86
ArrayIndexOutOfBoundException 9 68
replace a word with other 1 40
Opening PDF on button click and fill new document 2 19
INTRODUCTION Working with files is a moderately common task in Java.  For most projects hard coding the file names, using parameters in configuration files, or using command-line arguments is sufficient.   However, when your application has vi…
This was posted to the Netbeans forum a Feb, 2010 and I also sent it to Verisign. Who didn't help much in my struggles to get my application signed. ------------------------- Start The idea here is to target your cell phones with the correct…
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…
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:

920 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

14 Experts available now in Live!

Get 1:1 Help Now