Click to See Complete Forum and Search --> : String as variable object name


acemo
10-18-2006, 03:24 PM
I got a class CardDeck and a class Hand.
I wish to be able to rever with object to a CardDeck object aswell as to a Hand object.

example:

I make an CardDeck object called deck1
I make an Hand object Called hand1

The following command should let hand1 try to take a card from deck1:

hand1.takeCard("Ace", "red", "hearth", "deck1");

my code:

// ask other object if it has the card and take this card if it has.
// name, colour, type are parameters used to know wich card we are talking about.
// object is a parameter for choosing the object to ask the card we want.
// if the other object had the card, we now have the card in oure hand, return true.
// if the other object did not had the card, we dont have the card, return false.
public boolean takeCard(String name, String colour, String type, String object)
{
Card takeCard;
takeCard = object.giveCard("Jocker", "Jocker", "Jocker");
if(takeCard != null)
{
cards.add(takeCard);
return true;
}
else return false;
}


I noticed defining a string and then using this string as an object name does not work.
Is it possible to do what I am trying?

agent_x91
10-19-2006, 03:21 AM
You could use a java.util.Hashtable:


Hashtable decks=new Hashtable();
decks.put("deck1",deck1); //put a Deck object into the table, with the string "deck1" as a key to refer to it.

//when you want to get the object back from the string variable name, use:

Deck temp=(Deck)decks.get("deck1");