Right, I wasn't sure whether to put this here or in the java forum (since I'm trying this in java)
but in the end I figured it is probably a general coding question.
Hope I got it right :)
So, about object names :)
I'm trying to do the c++ forum coding exercise (in java) where you are supposed to model playing cards.
The thing is, I'd like the program to just create new card objects when needed,
instead of hardcoding every card.
How would I go around this?
(also I'm a rookie, so feel very free to comment on any kind of bad code I might have made)
Here is what I've got (which will hardcode the object names):
public enum Suit
{
HEARTS, CLUBS, SPADES, DIAMONDS
}
public enum Value
{
TWO, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING, ACE
}
public class card
{
// instance variables - replace the example below with your own
private Suit suit;
private Value value;
/**
* Constructor for objects of class card
*/
public card(Value value, Suit suit)
{
this.value = value;
this.suit = suit;
}
public void print()
{
System.out.println(this.value + "\tof " + this.suit);
}
}
import java.util.List;
import java.util.ArrayList;
import java.util.Random;
/**
* Write a description of class CardDeck here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class CardDeck
{
// instance variables - replace the example below with your own
private int cardsDealt;
private List<card> cardList;
private Random randGen = new Random();
/**
* Constructor for objects of class CardDeck
*/
public CardDeck()
{
// initialise instance variables
cardsDealt=0;
cardList = new ArrayList<card>();
}
public CardDeck(int cardsDealt)
{
this.cardsDealt = cardsDealt;
cardList = new ArrayList<card>();
}
public card draw()
{
int randomValue = randGen.nextInt(13) +1;
int randomSuit = randGen.nextInt(4);
Value value = null;
Suit suit = null;
switch(randomValue)
{
case 1: value = Value.ACE; break;
case 2: value = Value.TWO; break;
case 3: value = Value.THREE; break;
case 4: value = Value.FOUR; break;
case 5: value = Value.FIVE; break;
case 6: value = Value.SIX; break;
case 7: value = Value.SEVEN; break;
case 8: value = Value.EIGHT; break;
case 9: value = Value.NINE; break;
case 10: value = Value.TEN; break;
case 11: value = Value.JACK; break;
case 12: value = Value.QUEEN; break;
case 13: value = Value.KING; break;
}
switch(randomSuit)
{
case 0: suit = Suit.HEARTS; break;
case 1: suit = Suit.DIAMONDS; break;
case 2: suit = Suit.SPADES; break;
case 3: suit = Suit.CLUBS; break;
}
card card1 = new card(value, suit);
cardList.add(card1);
this.cardsDealt++;
return(card1);
}
public void print()
{
for (card c : cardList)
{
c.print();
}
}
}