I just started out trying to make a simple card game as of last night.
My problem is on line 16 and 17 of the first file. I have successfully created the 52 objects with variables for the cards, and once created they are placed into a Vector (the deck). Just to test it worked I used the below code, but the name is underlined and I get the error name cannot be resolved or is not a field.
Does anyone know why this may be? The objects are deffinately in the Vector, I just can't get to the variables they contain.
Thanks.
Code:
Object ob = (Object) Cards.deck.get(i);
System.out.println(ob.name);
****head.java
PHP Code:
import javax.swing.JOptionPane;
public class ****head {
public ****head() {
int p = 0; for (int i = 0; i < Cards.allCards.length; i++) { p = p != 13 ? p : 0; Cards card = new Cards();
It never will. Object is a base type that contains no properties, and your Card doesn't represent what it is.
You'll need to represent a card as an object, and a deck of Card. I'd represent the suit and value as an enum string pair:
PHP Code:
public class Card implements Comparable<Card> { public static enum Suit { HEART ("Hearts"), SPADE ("Spades"), CLUB ("Clubs"), DIAMOND ("Diamonds");
private final String sSuit;
Suit(String s) { this.sSuit = s; }
public String getSuit() { return this.sSuit; } }
public static enum FaceValue { ACE ("A"), TWO ("2"), THREE ("3"), FOUR ("4"), FIVE ("5"), SIX ("6"), SEVEN ("7"), EIGHT ("8"), NINE ("9"), TEN ("10"), JACK ("J"), QUEEN ("Q"), KING ("K");
private final String sValue;
FaceValue(String s) { this.sValue = s; }
public String getValue() { return this.sValue; } }
public class Deck extends ArrayList<Card> { private static final long serialVersionUID = 7465934980544707488L;
public static void main(String... argv) { Deck d = new Deck();
// Populate the deck with one of each suit and face value. for (Card.Suit s : Card.Suit.values()) { for (Card.FaceValue v : Card.FaceValue.values()) { d.add(new Card(s, v)); } }
Collections.shuffle(d); System.out.println("shuffled:"); for (Card c : d) { System.out.println(c); }
Collections.sort(d); System.out.println("sorted:"); for (Card c : d) { System.out.println(c); } } }
I like the enums since you can do a lot with them. It forces specific allowed entries and lets you run a switch on them unlike a string.
Edit:
Oh, btw I should mention simplicity as well. If you don't really care about a Deck or a Card, you can represent it just using the String array you have. That can be thrown into a list and Shuffled as well and print just as a string:
Wow, thanks Fou-Lu! I've tried your code and it works great. I understand what you're saying.
My first attempt actually used a String array and used the Collections.shuffle method, though I dropped it. I'm still struggling with classes and objects so this is pretty difficult understanding the best (and legal) approach.