Page 1 of 3 123 LastLast
Results 1 to 20 of 53
  1. #1
    sonny's Avatar
    sonny is offline Senior Member
    Join Date
    Feb 2010
    Location
    North West England
    Posts
    146
    Rep Power
    0

    Red face going round and round in class..

    the exercise seemed simple enough. but ive got hopelessly lost and confused myself no end. :confused:

    the exercise:
    Write a program that displays the name of a card randomly chosen from a complete deck of 52 playing cards. Each card consists of a rank (Ace, 2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen, King) and a suit (Clubs, Diamonds, Hearts, Spades). Your program should display the complete name of the card, as shown in the following sample run:
    i.e
    Queen of Spades.


    i started off with a random generator, declared two random ints && two Strings then wrote a method to covert the ints to the appropriate strings witha long series of If/if else statements... and it worked:D

    so completely ignoring any notions of premature optimisation I then thought, classes have a toString thing-a-ma-jig at the end,, that must be easier and as I have just started doing stuff with classes in my study text so perhaps thats what i should be doing.
    then i read a post about a card game and enum, we havent done enum but the links in the relevant posts made it look straightforward.

    it appears to me that enum is like declaring you own data type of special ints in the order that they occur.

    so off I went, but i cannot get the class playing card to work.
    I am not concerned with an array yet or producing one from the enum definitions... just getting the class to produce a random card when i pass the constructor with no params.
    so i could do a sort of guess the next card higher or lower kind of thing

    I have rgen in both, which is just as a reuslt of me playing about trying to get it to work. i realise it should not be in both.
    when i am experimenting i usually just comment out the things I am not testing.. so apologies if it looks messy i ve used php tags to try to make it more readable


    so after you've finished laughing your ass off at my feeble attempts if you could give me a shove in the right direction i should be most grateful.

    here is the class:
    PHP Code:
    import acm.util.*;
    
    public class PlayingCard {
    	/* Create an instance variable for the random number generator */
    	private RandomGenerator rgen = new RandomGenerator();
    	
    	/* enum representing the card Rank*/
    	public enum Rank { ACE, TWO, THREE, FOUR, FIVE, SIX,
            SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING }
    	
    	/* enum representing the card Suit*/
        public enum Suit {HEARTS, SPADES, DIAMONDS, CLUBS}
        
        /* Create instance variables for the rank and suit */
    	private final Rank rank;
        private final Suit suit;
        
        
        /**
         * Creates a playing card object  
         */
     // not the one i want to use but cant get it to work either it 
     // looks like these (Rank rank, Suit suit) are two method calls to return the rank and suit.
    	public PlayingCard(Rank rank, Suit suit){
    		this.rank = rank; //  = rgen.nextInt(1,13)
    		this.suit = suit;  
    	}
    	
    	public PlayingCard(){// get an error msg from eclipse about suit not being initialised
    		int rank = rgen.nextInt(1,13); // im tring to intialise with rgen
    		int suit = rgen.nextInt(1,4); 
    		}
    	 
    	
    	public String toString() { 
        	return rank + " of " + suit; 
        	}
    	/*methods  */
    	public Rank rank() { 
    		return rank; 
    		}
    	public Suit suit() { 
    		return suit; 
    		}
    	/* don't think i need these as yet */
    	public Rank getRank(){
    		return rank;
    	}
    	public Suit getSuit(){
    		return suit;
    	}
    }
    and here is the the run method,


    PHP Code:
    public void run(){
    		getCard();
    		tryToUseAClass();
    	}
    
    	private void tryToUseAClass() {
    		PlayingCard random = new PlayingCard();
    		
    		/* just other bits & ideas i played with */
    		int rank = rgen.nextInt(1,13);
    		int suit = rgen.nextInt(1,4);
    		PlayingCard IntsPassed = new PlayingCard(rank,suit);
    		
    		PlayingCard anotherTry = new PlayingCard(enum Rank rank,enum Suit suit); 
    		
    		
    		println( random );
    		
    	}
    
    	/*  Uses rgen to generate random values to initialise rank and suit*/
    	private void getCard() {
    		int rank = rgen.nextInt(1,13);
    		int suit = rgen.nextInt(1,4);
    		String rankStr =(" none ");
    		String suitStr =(" None ");
    		getCardString(rank, suit, rankStr, suitStr);
    	}
    		
      /* long set of If else to define the rank string*/ 
    	private void getCardString(int rank, int suit, String rankStr, String suitStr) {
    		if ( 1 == rank ) rankStr = (" Ace ");
    		else if ( 2 == rank ) rankStr = (" Two ");
    		
                    /*  more lines.....*/
    
    		else if ( 13 == rank ) rankStr = (" King ");
    		
    	/*  if else to define the suit string*/	
    		if ( 1 == suit )suitStr = (" Hearts ");
    		
            /*  more   lines    */
    
    	/* finally prints the rank and suit string*/	
    		println(rankStr + "of" + suitStr);
    	}
    }
    :p I still have my "L" plates on...... directions and explanations are far more help than blaring your Horn! :p Watching:CS106a on YouTube \Reading The Art & Science of Java by Eric S Roberts

  2. #2
    gcalvin is offline Senior Member
    Join Date
    Mar 2010
    Posts
    952
    Rep Power
    5

    Default

    I think you're confusing a Card and a Deck. Think about the essence of a Card -- what properties does it comprise? What does it "know" about itself?

    The idea of enums is a good one, but since no individual Card can have more than one rank or more than one suit, it seems to me that the enums should be static -- they belong to the general idea of a Card (so to the class Card), not to any specific Card.

    Similarly, there is nothing random about a Card. There could be something random about a Deck of Cards (one that knows how to shuffle itself, for instance). But think about how shuffling works -- individual Cards are not randomly assigned values and ranks. Rather, each card has one specific value and rank, and their order in the Deck is randomized.

    Good luck! You're not as far off as you think.

    -Gary-

  3. #3
    sonny's Avatar
    sonny is offline Senior Member
    Join Date
    Feb 2010
    Location
    North West England
    Posts
    146
    Rep Power
    0

    Post hmmmmm

    thanks gary..

    okay i think that,

    the class is PlayingCard and not DeckofCards (but i still need all the ranks and suits)

    ive been thinking im trying to create a new card each time, which i think is where ive been getting confused...
    (but,, i could have three instances of card,, but they could potentially all be the Ace of Spades so ..... )

    I should be just trying to randomly change the state of the card that i have

    so i think i am a ways off yet

    but i need to change the enums to static
    like this?
    Java Code:
    private enum static Rank{.....}
    and i need a setter to reset the rank and suit each time i want to randomise the card

    or should i think of the class being DeckOfCards..... no thats probably stretching it a bit far isnt it.
    :p I still have my "L" plates on...... directions and explanations are far more help than blaring your Horn! :p Watching:CS106a on YouTube \Reading The Art & Science of Java by Eric S Roberts

  4. #4
    gcalvin is offline Senior Member
    Join Date
    Mar 2010
    Posts
    952
    Rep Power
    5

    Default

    No, I don't think a Deck class is stretching it at all. I think you are fogging your thinking by trying to do everything in a PlayingCard class. I think you should at least have a PlayingCard class and a DeckOfCards class and maybe a CardGame class or something as well. Let your PlayingCard be just a PlayingCard.

    There is nothing random about an individual PlayingCard -- it is what it is, and it stays that way from the time it comes off the printing press until the time it is discarded in a Las Vegas dumpster. Therefore your PlayingCard class should have a constructor that takes a rank and a suit, but no setters -- it doesn't make any sense to set a rank or a suit on a card that already exists (unless it's a Joker -- maybe you'll write a Joker subclass one day). Randomness only comes into play when you are shuffling a DeckOfCards.

    Study some more about Enum Types -- they're more powerful than you've noticed.

    Enum Types (The Java™ Tutorials > Learning the Java Language > Classes and Objects)

    Note that they are Objects, so they have a toString() method, and there's also a static values() method for each type, which returns an array of the individual values (such as HEARTS, SPADES, DIAMONDS, CLUBS). This means you don't need to do the if...else and "rank string" "suit string" stuff you're trying to do.

    Trim the excess from your PlayingCard class, and then write a main() for it that just creates a single card -- say an Ace of Spades -- and prints it out. Then try writing your DeckOfCards class. You'll need storage for 52 PlayingCards -- hint: an ArrayList will make your shuffle() method easiest. All you should need for this class is a constructor, the void shuffle() method, and maybe a toString() that prints a list of all the cards. I guess you'll probably want a PlayingCard deal() method (or getNext() -- whichever makes more sense to you) which means you'll need to store the index of the card that's currently on top of the deck, and maybe how many cards have been dealt so far, and how many remain. Maybe you want getters for those as well. Then write a main() for your DeckOfCards class that creates a new DeckOfCards, prints it out, shuffles it, and prints it out again.

    That should keep you busy until we get a chance to discuss it some more.

    -Gary-

  5. #5
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,785
    Blog Entries
    7
    Rep Power
    21

    Default

    Also read this relatively 'old' tutorial (it's a Java 1.5 tutorial); it contains a complete spoiler so take care ;-)

    btw. Nested Enum classes are implicitly static (that's a compiler thingy) so you don't have to write "static enum Rank ..." etc. See this link.

    kind regards,

    Jos

  6. #6
    gcalvin is offline Senior Member
    Join Date
    Mar 2010
    Posts
    952
    Rep Power
    5

    Default

    Quote Originally Posted by JosAH View Post
    btw. Nested Enum classes are implicitly static (that's a compiler thingy) so you don't have to write "static enum Rank ..." etc.
    Thanks for that -- it's good to know!

    -Gary-

  7. #7
    sonny's Avatar
    sonny is offline Senior Member
    Join Date
    Feb 2010
    Location
    North West England
    Posts
    146
    Rep Power
    0

    Default

    Quote Originally Posted by JosAH View Post
    it contains a complete spoiler so take care
    i think i'm more confused than before!!!
    but thats okay im sure i can crack it!

    Quote Originally Posted by gcalvin View Post
    There is nothing random about an individual PlayingCard --....
    ..... Randomness only comes into play when you are shuffling a DeckOfCards.
    So does that mean i dont need randomgenerator in PlayingCard()??


    Sonny is thinking out loud
    Deck of cards is a class,, it contains or creates(potentially) 52 playing cards ,, its method will create? or store? those 52 playingcards in the order defined by the enum declaration,, with some sort of nested for loops. and another method will shuffle them... another method to deal the next card,,

    OR deck of cards /(Deck of Values) contains? or creates? 52 somethings...( 1, 1) and (1,2) etc... any of which when passed to playing card will create a playing card (Ace Hearts) etc.. and that means enum declaration needs to be in PlayingCard not in deck,, rgen needs to be in the deck not playing card,
    and for now my run method can just draw a card by asking the deck for the next value,, which it gives to playing card, which displays it,,

    okay think i'm getting warmer... just time for a few experiments before the kids get home.
    Last edited by sonny; 03-31-2010 at 04:27 PM.
    :p I still have my "L" plates on...... directions and explanations are far more help than blaring your Horn! :p Watching:CS106a on YouTube \Reading The Art & Science of Java by Eric S Roberts

  8. #8
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,224
    Rep Power
    20

    Default

    You are getting warmer...and you're starting to think in terms of objects.
    I'd go with your first "thinking out loud"...it's the more OO of the two.
    Generating the cards, via enums, should be relatively easy (see EnumSet).

    And then it's a case, as you say, of shuffling and dealing.

    ETA: In fact, if you want to get really fancy pants, define the Deck as an interface initially and force yourself to think simply in terms of the Deck should be able to do. You've already started on that path in any case. Then simply provide an implementation of that interface. It's good coding practice in Java.

  9. #9
    sonny's Avatar
    sonny is offline Senior Member
    Join Date
    Feb 2010
    Location
    North West England
    Posts
    146
    Rep Power
    0

    Thumbs up

    i got as far as

    Java Code:
    /* Construct the deck */
    	public DeckOfCards(){
    		for (int ranksInDeck = 1; ranksInDeck <=13; ranksInDeck++){
    			for (int suitsInDeck = 1; suitsInDeck <=4; suitsInDeck++){
    				storeValueInAnArray(ranksInDeck,suitsInDeck);
    				
    			}
    		}
    		
    	}
    but i need to have the enum declaration in the deck,,
    ( whats handicapping me a little bit is enum and defining arrays are brand new ideas that i'm not upto yet,, but thats cool you still gotta learn it)

    so whats the point of even having PlayingCard() ??
    is that what you mean here??
    define the Deck as an interface initially
    but i would need an object i could refer to in a cardGame()...actually never mind that for now! for now Im concentrating just on Deck.

    okay thanks for that
    :p I still have my "L" plates on...... directions and explanations are far more help than blaring your Horn! :p Watching:CS106a on YouTube \Reading The Art & Science of Java by Eric S Roberts

  10. #10
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,224
    Rep Power
    20

    Default

    OK, so you know that you want an array of cards, and that a card is defined by a suit and a value, which themselves are each enums (as you defined above).

    Now, I stuck a link for EnumSet in my previous post. Now, this may be a big leap, but this will get you into the concept of the Java Collections framework. EnumSet gives you access to a method that will take your enum class name and give you a Set back. You can iterate (for loop) over that Set. So you can iterate over the Values enumset, and inside that the Suit set...and inside that loop create a Card, with that Value and Suit...and stick that in yiur array.

  11. #11
    gcalvin is offline Senior Member
    Join Date
    Mar 2010
    Posts
    952
    Rep Power
    5

    Default

    OK, it's a bit of a spoiler, but you're going to like this a lot. Because of the way enums work, you can do this:
    Java Code:
            for (PlayingCard.Suit suit : PlayingCard.Suit.values()) {
                    ...
            }
    The values() method gives you an array containing the four suits in PlayingCard.Suit. Each time through the loop, the suit variable is assigned one of those four values. And of course the same construct will work for PlayingCard.Rank. (This is assuming both enums are declared in your PlayingCard class, which is where they belong.) This is called a "for-each loop" and was introduced in Java 5. You should use it instead of an int index for loop wherever you can.

    I think it's a bit early for you to concern yourself with Interfaces. Save that for a later lesson.

    Also, don't forget the new operator -- that's what you'll need for instantiating PlayingCard objects within your loop.

    I'm going to post my Deck() constructor, but in white text -- try not to read it, but it's there if you get into a jam. First just notice its length -- that should confirm for you that you are on the right track. There are a couple of syntactic things that may not be obvious, so don't be too reluctant to look.
    Java Code:
    [COLOR="White"]	public Deck() {
    		cards = new ArrayList<Card>();
    		for (Card.Suit suit : Card.Suit.values()) {
    			for (Card.Rank rank : Card.Rank.values()) {
    				cards.add(new Card(rank, suit));
    			}
    		}
    		topCardIndex = 0;
    	}
    [/COLOR]
    -Gary-

  12. #12
    gcalvin is offline Senior Member
    Join Date
    Mar 2010
    Posts
    952
    Rep Power
    5

    Default

    Quote Originally Posted by Tolls View Post
    Now, I stuck a link for EnumSet in my previous post. Now, this may be a big leap, but this will get you into the concept of the Java Collections framework. EnumSet gives you access to a method that will take your enum class name and give you a Set back. You can iterate (for loop) over that Set. So you can iterate over the Values enumset, and inside that the Suit set...and inside that loop create a Card, with that Value and Suit...and stick that in yiur array.
    You don't even need EnumSet because enums automatically have the values() method, which returns an array (and should be all Sonny needs for now).

    -Gary-

  13. #13
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,224
    Rep Power
    20

    Default

    Gah!
    This is what happens when I'm stuck doing requirements...my brains start to dribble out.

  14. #14
    sonny's Avatar
    sonny is offline Senior Member
    Join Date
    Feb 2010
    Location
    North West England
    Posts
    146
    Rep Power
    0

    Thumbs up

    i think i have a constructor now.

    i think upto now the class works like this:
    i have a random generator IVAR
    and an array list IVAR called CARDS_IN_DECK
    but array list is empty at the moment.


    Java Code:
    import java.util.*;  //  doh!  red lines everywhere,, (30 mins later) oh yes libraries:o  
    import acm.util.*;
            public class DeckOfCards {
    	/* Create an instance variable for the random number generator */
    	private RandomGenerator rgen = new RandomGenerator();
    	
            /*  create instance variables for the 52 cards */
    	private ArrayList <PlayingCard> CARDS_IN_DECK = new ArrayList<PlayingCard>();
    my constructor (which is just a kind of method right??), a method that initialises the object. looks like this
    Java Code:
    /* Construct the deck */
    	private DeckOfCards(){
    		for(PlayingCard.Suit suit : PlayingCard.Suit.values()){
    			for(PlayingCard.Rank rank : PlayingCard.Rank.values()){
    				CARDS_IN_DECK.add(new PlayingCard(rank, suit));
    			}
    		}
    	}
    It basically iterates through the enums Rank and Suit fields defined in PlayingCard().
    and creates a new PlayingCard(for each rank * each suit) which it adds to the Array list CARDS_IN_DECK..
    i peeked at the white text and noticed garys constructor was a little differnt because it declares the new array list in the constructor and not as an IVAR
    the lifetime of the IVAR is the the lifetime of the instance of the class,, i think,, hmmm... in a potential CardGame() are the cards in the Deck or in a hand where do they go when the hand is over,, might have something to do with where the list is declared.

    so now my array list should have all the cards in it,
    but the cards will be in order Ace hearts, Two Hearts and so on the order decided by the enum fields and the nested for-each statements.

    but im not much further forward than that:(

    Apart from ive just managed to print out the array
    i haven,t even begun to think about shuffling or dealing Yet!
    :p I still have my "L" plates on...... directions and explanations are far more help than blaring your Horn! :p Watching:CS106a on YouTube \Reading The Art & Science of Java by Eric S Roberts

  15. #15
    gcalvin is offline Senior Member
    Join Date
    Mar 2010
    Posts
    952
    Rep Power
    5

    Default

    Quote Originally Posted by sonny View Post
    i peeked at the white text and noticed garys constructor was a little differnt because it declares the new array list in the constructor and not as an IVAR
    the lifetime of the IVAR is the the lifetime of the instance of the class,, i think,, hmmm... in a potential CardGame() are the cards in the Deck or in a hand where do they go when the hand is over,, might have something to do with where the list is declared.
    No, actually mine is declared as an ivar as well, but initialized in the constructor. This is an idiosyncracy of mine -- I don't like to initialize non-static ivars outside the constructor. It just helps me keep things clear in my mind, reminding me that when a new Deck is created, its own ArrayList is set up and filled with cards. Initializing it outside the constructor while declaring it is perfectly valid practice, so I don't say that people who do it that way are wrong. I just prefer to do the initialization in the constructor.

    Your code is fine, although I would quibble with the name CARDS_IN_DECK. You're better off if you reserve all-caps names to constants. This array is not a constant, and in fact you're going to be shuffling it shortly. I'd tend to just call it "cards" or maybe "playingCards". Keep in mind when you're naming things that in object-oriented programming, the scope of your names is pretty well limited. This array, for instance, is going to be private, so nothing beyond this immediate class will see this name. That gives you the freedom to keep names simple -- it's not going to be confused with some other "cards" variable someplace else.

    Also, you've made your constructor private, which means that other classes will not be able to create a new DeckOfCards(). I know the access modifiers are confusing, but generally you want ivars and "helper methods" to be private, constructors and methods that are part of your "published API" (that just means methods that you want other classes to be able to use) to be public. You'd mark things as protected only in rare cases, where you don't want them public, but you anticipate that a subclass might be able to use it. For instance, you might think of creating a protected setRank() and setSuit() on your PlayingCard class, anticipating that a future Joker or WildCard subclass might want to set its rank and suit on the fly.

    Shuffling is going to be surprisingly easy. You'll start by randomly choosing one of the 52 elements in your ArrayList, remove()ing it, and add()ing it on to the end. Then you do the same thing again, except choosing from among the first 51 elements, then 50, 49, etc. You could do it in two lines of code, but use five or six to keep it clear. ;)

    -Gary-

  16. #16
    gcalvin is offline Senior Member
    Join Date
    Mar 2010
    Posts
    952
    Rep Power
    5

    Default

    By the way, Sonny, have you worked through this tutorial yet?

    Eclipse and Java for Total Beginners

    If you haven't, I strongly recommend doing it now. It's 16 bit-sized lessons, totalling less than four hours. It covers an earlier version of Eclipse, but everything still applies, with some very minor changes (let me know if there's anything you can't find in the current Eclipse version). He uses some very simple and concrete examples, while demonstrating lots of cool Eclipse tricks. It will really help things click into place for you.

    -Gary-

  17. #17
    sonny's Avatar
    sonny is offline Senior Member
    Join Date
    Feb 2010
    Location
    North West England
    Posts
    146
    Rep Power
    0

    Lightbulb

    Quote Originally Posted by gcalvin View Post
    No, actually mine is declared as an ivar as well, but initialized in the constructor. This is an idiosyncracy of mine -- I don't like to initialize non-static ivars outside the constructor. It just helps me keep things clear in my mind, reminding me that when a new Deck is created, its own ArrayList is set up and filled with cards. Initializing it outside the constructor while declaring it is perfectly valid practice, so I don't say that people who do it that way are wrong. I just prefer to do the initialization in the constructor.
    Okay i get that i now have this,
    Java Code:
    /*  create instance variables for the 52 values */
    	private ArrayList <PlayingCard> cards;
    	
    	
    	/* Construct the deck */
    	public DeckOfCards(){
    		cards = new ArrayList<PlayingCard>();
    		for(PlayingCard.Suit suit : PlayingCard.Suit.values()){
    			for(PlayingCard.Rank rank : PlayingCard.Rank.values()){
    				cards.add(new PlayingCard(rank, suit));
    			}
    		}
    	}
    Quote Originally Posted by gcalvin View Post
    Also, you've made your constructor private, which means that other classes will not be able to create a new DeckOfCards().
    fixed that and understand

    Quote Originally Posted by gcalvin View Post
    Shuffling is going to be surprisingly easy. You'll start by randomly choosing one of the 52 elements in your ArrayList, remove()ing it, and add()ing it on to the end. Then you do the same thing again, except choosing from among the first 51 elements, then 50, 49, etc. You could do it in two lines of code, but use five or six to keep it clear. ;)
    okay i have two methods but one is cheating
    Java Code:
    public void easyShuffle(){
    		Collections.shuffle(cards);
    	}
    	
    	
    	public void shuffleDeck(){
    			int i = rgen.nextInt(1,cards.size());
    			int j = rgen.nextInt(1,cards.size());
    			PlayingCard temp = cards.get(i);
    			cards.set(i, cards.get(j));
    			cards.set(j, temp);
    		}
    i tried to put shuffleDeck in a for loop with (cards) iterations but i get errors
    but i think i know why sort of..
    if i swap card 8 with card 22 then i cant swap those cards again in the loop with another card,, now ive seen your post i think i know how to fix this..

    and ive statrted to get a few ideas about dealing

    Good Times!! as Mehran would say:D
    :p I still have my "L" plates on...... directions and explanations are far more help than blaring your Horn! :p Watching:CS106a on YouTube \Reading The Art & Science of Java by Eric S Roberts

  18. #18
    gcalvin is offline Senior Member
    Join Date
    Mar 2010
    Posts
    952
    Rep Power
    5

    Default

    Quote Originally Posted by sonny View Post
    okay i have two methods but one is cheating
    Java Code:
    public void easyShuffle(){
    		Collections.shuffle(cards);
    	}
    That's not cheating, that's just being smart! Kudos for reading the docs -- that's another method I didn't know about.

    -Gary-

  19. #19
    sonny's Avatar
    sonny is offline Senior Member
    Join Date
    Feb 2010
    Location
    North West England
    Posts
    146
    Rep Power
    0

    Lightbulb

    Quote Originally Posted by gcalvin View Post
    That's not cheating, that's just being smart! Kudos for reading the docs -- that's another method I didn't know about.

    -Gary-
    but i learned not a lot!

    i now have
    Java Code:
    public void shuffleDeck(){
    		for (int k = 0; k < cards.size();k++){
    			int i = rgen.nextInt(1,(cards.size()-k));
    			cards.set(i, cards.get(cards.size()));
    			}
    	}
    but still getting out of bounds errors hmmm!

    i need to remove it then put it back at the end!!

    EDIT: well blow me down and call me croupier
    Java Code:
    public void shuffleDeck(){
    		for (int k = 0; k < cards.size();k++){
    			int i = rgen.nextInt(1,(cards.size()-k));
    			PlayingCard temp = cards.get(i);
    			cards.remove(i);
    			cards.add(temp);
    			}
    	}
    well you can call me a croupier once i can deal!!
    next for dealing
    Last edited by sonny; 04-01-2010 at 04:21 AM.
    :p I still have my "L" plates on...... directions and explanations are far more help than blaring your Horn! :p Watching:CS106a on YouTube \Reading The Art & Science of Java by Eric S Roberts

  20. #20
    gcalvin is offline Senior Member
    Join Date
    Mar 2010
    Posts
    952
    Rep Power
    5

    Default

    Quote Originally Posted by sonny View Post
    EDIT: well blow me down and call me croupier
    Java Code:
    public void shuffleDeck(){
    		for (int k = 0; k < cards.size();k++){
    			int i = rgen.nextInt(1,(cards.size()-k));
    			PlayingCard temp = cards.get(i);
    			cards.remove(i);
    			cards.add(temp);
    			}
    	}
    well you can call me a croupier once i can deal!!
    next for dealing
    Excellent! But you can go even simpler:
    Java Code:
            public void shuffleDeck() {
                    for (int k = cards.size(); k > 0; k--) {
                            int i = rgen.nextInt(k);
                            PlayingCard temp = cards.remove(i);
                            cards.add(temp);
                    }
            }
    You could reduce that by two more lines, but I'll leave that as an exercise.

    -Gary-

Page 1 of 3 123 LastLast

Similar Threads

  1. round to two decimal places
    By javaMike in forum New To Java
    Replies: 3
    Last Post: 12-24-2011, 03:01 AM
  2. stopping second time round
    By silverspoon34 in forum New To Java
    Replies: 0
    Last Post: 11-20-2009, 03:04 PM
  3. How to Draw Round Rectangles in SWT
    By Java Tip in forum SWT Tips
    Replies: 0
    Last Post: 06-28-2008, 10:25 PM
  4. How to round a double?
    By Valeriano in forum New To Java
    Replies: 1
    Last Post: 05-31-2007, 04:50 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •