Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.java.programmer > #29504 > unrolled thread

Help with Deck of cards assignment and getting it to deal...

Started byScott Dunning <scottwd01@gmail.com>
First post2014-08-01 18:16 -0700
Last post2014-08-31 17:31 +0100
Articles 20 on this page of 60 — 12 participants

Back to article view | Back to comp.lang.java.programmer


Contents

  Help with Deck of cards assignment and getting it to deal... Scott Dunning <scottwd01@gmail.com> - 2014-08-01 18:16 -0700
    Re: Help with Deck of cards assignment and getting it to deal... Roedy Green <see_website@mindprod.com.invalid> - 2014-08-02 01:42 -0700
      Re: Help with Deck of cards assignment and getting it to deal... Martin Gregorie <martin@address-in-sig.invalid> - 2014-08-02 10:19 +0000
        Re: Help with Deck of cards assignment and getting it to deal... Roedy Green <see_website@mindprod.com.invalid> - 2014-08-03 15:54 -0700
          Re: Help with Deck of cards assignment and getting it to deal... Martin Gregorie <martin@address-in-sig.invalid> - 2014-08-04 13:00 +0000
            Re: Help with Deck of cards assignment and getting it to deal... Arne Vajhøj <arne@vajhoej.dk> - 2014-08-19 17:48 -0400
              Re: Help with Deck of cards assignment and getting it to deal... "Chris Uppal" <chris.uppal@metagnostic.REMOVE-THIS.org> - 2014-08-20 10:48 +0100
                Re: Help with Deck of cards assignment and getting it to deal... Arne Vajhøj <arne@vajhoej.dk> - 2014-09-07 21:42 -0400
                Re: Help with Deck of cards assignment and getting it to deal... Eric Sosman <esosman@comcast-dot-net.invalid> - 2014-09-07 22:04 -0400
                  Re: Help with Deck of cards assignment and getting it to deal... Arne Vajhøj <arne@vajhoej.dk> - 2014-09-07 22:08 -0400
    Re: Help with Deck of cards assignment and getting it to deal... Mike Amling <mamling@chaff.us> - 2014-08-03 07:38 -0500
    Re: Help with Deck of cards assignment and getting it to deal... Eric Sosman <esosman@comcast-dot-net.invalid> - 2014-08-03 10:23 -0400
      Re: Help with Deck of cards assignment and getting it to deal... lipska the kat <lipskathekat@example.com> - 2014-08-03 18:52 +0100
        Re: Help with Deck of cards assignment and getting it to deal... Jeff Higgins <jeff@invalid.invalid> - 2014-08-03 14:16 -0400
          Re: Help with Deck of cards assignment and getting it to deal... lipska the kat <lipskathekat@example.com> - 2014-08-03 19:21 +0100
            Re: Help with Deck of cards assignment and getting it to deal... Jeff Higgins <jeff@invalid.invalid> - 2014-08-03 14:38 -0400
              Re: Help with Deck of cards assignment and getting it to deal... lipska the kat <lipskathekat@example.com> - 2014-08-03 19:41 +0100
      Re: Help with Deck of cards assignment and getting it to deal... Mike Amling <mamling@chaff.us> - 2014-08-03 16:05 -0500
    Re: Help with Deck of cards assignment and getting it to deal... Jeff Higgins <jeff@invalid.invalid> - 2014-08-03 11:08 -0400
      Re: Help with Deck of cards assignment and getting it to deal... Eric Sosman <esosman@comcast-dot-net.invalid> - 2014-08-03 11:41 -0400
        Re: Help with Deck of cards assignment and getting it to deal... Jeff Higgins <jeff@invalid.invalid> - 2014-08-03 13:25 -0400
          Re: Help with Deck of cards assignment and getting it to deal... Jeff Higgins <jeff@invalid.invalid> - 2014-08-03 13:36 -0400
            Re: Help with Deck of cards assignment and getting it to deal... David Postill <david.postill@gmail.com> - 2014-08-04 09:00 +0200
          Re: Help with Deck of cards assignment and getting it to deal... Jeff Higgins <jeff@invalid.invalid> - 2014-08-03 13:47 -0400
            Re: Help with Deck of cards assignment and getting it to deal... Jeff Higgins <jeff@invalid.invalid> - 2014-08-03 13:52 -0400
              Re: Help with Deck of cards assignment and getting it to deal... Jeff Higgins <jeff@invalid.invalid> - 2014-08-03 14:10 -0400
          Re: Help with Deck of cards assignment and getting it to deal... Eric Sosman <esosman@comcast-dot-net.invalid> - 2014-08-03 15:00 -0400
            Re: Help with Deck of cards assignment and getting it to deal... Arne Vajhøj <arne@vajhoej.dk> - 2014-08-03 15:26 -0400
              Re: Help with Deck of cards assignment and getting it to deal... lipska the kat <lipskathekat@example.com> - 2014-08-03 20:34 +0100
              Re: Help with Deck of cards assignment and getting it to deal... Eric Sosman <esosman@comcast-dot-net.invalid> - 2014-08-03 16:49 -0400
                Re: Help with Deck of cards assignment and getting it to deal... Arne Vajhøj <arne@vajhoej.dk> - 2014-08-03 17:01 -0400
                  Re: Help with Deck of cards assignment and getting it to deal... "Chris Uppal" <chris.uppal@metagnostic.REMOVE-THIS.org> - 2014-08-04 20:32 +0100
                    Re: Help with Deck of cards assignment and getting it to deal... Arne Vajhøj <arne@vajhoej.dk> - 2014-08-19 17:45 -0400
                      Re: Help with Deck of cards assignment and getting it to deal... "Chris Uppal" <chris.uppal@metagnostic.REMOVE-THIS.org> - 2014-08-20 10:50 +0100
                        Re: Help with Deck of cards assignment and getting it to deal... Brixomatic <brixomatic@yahoo.com> - 2014-08-31 10:17 +0200
                          Re: Help with Deck of cards assignment and getting it to deal... "Chris Uppal" <chris.uppal@metagnostic.REMOVE-THIS.org> - 2014-09-04 15:14 +0100
                            Re: Help with Deck of cards assignment and getting it to deal... Eric Sosman <esosman@comcast-dot-net.invalid> - 2014-09-04 10:55 -0400
                              Re: Help with Deck of cards assignment and getting it to deal... "Chris Uppal" <chris.uppal@metagnostic.REMOVE-THIS.org> - 2014-09-04 16:12 +0100
                                [OT] Re: Help with Deck of cards assignment and getting it to deal... Eric Sosman <esosman@comcast-dot-net.invalid> - 2014-09-04 15:05 -0400
                              Re: Help with Deck of cards assignment and getting it to deal... Gene Wirchenko <genew@telus.net> - 2014-09-05 10:03 -0700
                        Re: Help with Deck of cards assignment and getting it to deal... Arne Vajhøj <arne@vajhoej.dk> - 2014-09-07 21:45 -0400
                          Re: Help with Deck of cards assignment and getting it to deal... Eric Sosman <esosman@comcast-dot-net.invalid> - 2014-09-07 22:13 -0400
                Re: Help with Deck of cards assignment and getting it to deal... Jeff Higgins <jeff@invalid.invalid> - 2014-08-03 17:19 -0400
                  Re: Help with Deck of cards assignment and getting it to deal... Eric Sosman <esosman@comcast-dot-net.invalid> - 2014-08-04 08:14 -0400
                    Re: Help with Deck of cards assignment and getting it to deal... Jeff Higgins <jeff@invalid.invalid> - 2014-08-04 20:03 -0400
                      Re: Help with Deck of cards assignment and getting it to deal... Jeff Higgins <jeff@invalid.invalid> - 2014-08-04 20:29 -0400
            Re: Help with Deck of cards assignment and getting it to deal... Jeff Higgins <jeff@invalid.invalid> - 2014-08-03 15:45 -0400
              Re: Help with Deck of cards assignment and getting it to deal... Jeff Higgins <jeff@invalid.invalid> - 2014-08-03 16:01 -0400
                Re: Help with Deck of cards assignment and getting it to deal... Eric Sosman <esosman@comcast-dot-net.invalid> - 2014-08-03 17:05 -0400
                  Re: Help with Deck of cards assignment and getting it to deal... Jeff Higgins <jeff@invalid.invalid> - 2014-08-03 17:37 -0400
                    Re: Help with Deck of cards assignment and getting it to deal... Jeff Higgins <jeff@invalid.invalid> - 2014-08-03 18:19 -0400
                      Re: Help with Deck of cards assignment and getting it to deal... Jeff Higgins <jeff@invalid.invalid> - 2014-08-03 18:34 -0400
                        Re: Help with Deck of cards assignment and getting it to deal... Eric Sosman <esosman@comcast-dot-net.invalid> - 2014-08-03 20:37 -0400
                          Re: Help with Deck of cards assignment and getting it to deal... Jeff Higgins <jeff@invalid.invalid> - 2014-08-03 20:40 -0400
                            Re: Help with Deck of cards assignment and getting it to deal... Jeff Higgins <jeff@invalid.invalid> - 2014-08-03 20:49 -0400
                  Re: Help with Deck of cards assignment and getting it to deal... Jeff Higgins <jeff@invalid.invalid> - 2014-08-03 18:09 -0400
    Re: Help with Deck of cards assignment and getting it to deal... Roedy Green <see_website@mindprod.com.invalid> - 2014-08-04 18:43 -0700
      Re: Help with Deck of cards assignment and getting it to deal... "Chris Uppal" <chris.uppal@metagnostic.REMOVE-THIS.org> - 2014-08-05 11:19 +0100
        Re: Help with Deck of cards assignment and getting it to deal... "Chris Uppal" <chris.uppal@metagnostic.REMOVE-THIS.org> - 2014-08-05 11:28 +0100
    Re: Help with Deck of cards assignment and getting it to deal... lipska the kat <lipskathekat@example.com> - 2014-08-31 17:31 +0100

Page 1 of 3  [1] 2 3  Next page →


#29504 — Help with Deck of cards assignment and getting it to deal...

FromScott Dunning <scottwd01@gmail.com>
Date2014-08-01 18:16 -0700
SubjectHelp with Deck of cards assignment and getting it to deal...
Message-ID<lrhe0d$l3n$1@dont-email.me>
Hello, I have an assignment for my summer class.  FYI, I'm super new to 
programming in general and this is my first time with java and it's a 
summer class so it's going super fast (please be nice!) lol.

Basically I started writing my code in one class, then I split it up 
into a Card class and a DeckOfCards class and I now need to figure out 
how to get it all to work together.  I get a little confused with 
calling methods sometimes, especially when separate classes are in play. 
  I think I just need a method to deal out five cards that also tells 
how many cards are left in the deck.  Then get it all working together 
correctly.  Also, I need a toString method but I honestly do not know 
how to go about that.  Any help is greatly appreciated!  If you could 
help explain things too that would be awesome!  I think I have 
everything SO FAR correct but I could be wrong and I'm sure there are 
better ways to write the code, I'll take any suggestions for a cleaner 
look too.  FYI, I think the prof would rather arrays then enums since 
we're dealing with arrays right now.

Here are the directions...
Design and implement a class called Card that represents a standard 
playing card. Each card has a suit and a face value. Then create a class 
called DeckOfCards that stores 52 objects of the Card class. Include 
methods to shuffle the deck, deal a card and report the number of cards 
left in the deck. The shuffle methods should assume a full deck. Create 
a driver class (CardsGame) with a main method that deals five cards from 
the shuffled deck, printing each card as it is dealt. Make sure to write 
the appropriate constructors, getters, setters, toString and other 
methods as required for both classes.


The main class, CardsGame Class

     import java.util.Scanner;

     public class CardsGame {
         public static void main (String [] args) {

        }
     }

Card Class

     class Card {
        public static final int SPADE   = 4;
        public static final int HEART   = 3;
        public static final int CLUB    = 2;
        public static final int DIAMOND = 1;

        private int rank;
        private int suit;
        private static final String[] Suit = {"Hearts", "Clubs", 
"Spades", "Diamonds"};
        private static final String[] Rank = {"Ace", "2", "3", "4", "5", 
"6", "7", "8", "9", "10", "Jack", "Queen", "King"};

        private int cardSuit;
        private int cardRank;

        public Card(int suit, int rank) {
           if (rank == 1)
              cardRank = 14;     // Give Ace the rank 14
           else
              cardRank = (int) rank;
              cardSuit = (int) suit;
        }

        public int suit() {
           return this.cardSuit;
        }

        public String suitStr() {
           return(this.Suit[ this.cardSuit ]); 

        }

        public int rank() {
           return this.cardRank;
        }

        public String rankStr() {
           return ( Rank[ cardRank ] );
        }


        public String toString() {
           return ( Rank[ cardRank ] + Suit[ cardSuit ] );
        }
     }

DeckOfCards Class

     class DeckOfCards {
        public static final int NEWCARDS = 52;
        private Card[] deckOfCards;         // Contains all 52 cards
        private int currentCard;            // deal THIS card in deck

     public DeckOfCards( ) {
       deckOfCards = new Card[NEWCARDS];
       int i = 0;

       for ( int suit = Card.DIAMOND; suit <= Card.SPADE; suit++ )
          for ( int rank = 1; rank <= 13; rank++ )
              deckOfCards[i++] = new Card(suit, rank);
              currentCard = 0;
      }


        //shuffle(n): shuffle the deck
        public void shuffle(int n) {
           int i, j, k;
           for ( k = 0; k < n; k++ ) {
	          i = (int) ( NEWCARDS * Math.random() );  // Pick 2 random cards
	          j = (int) ( NEWCARDS * Math.random() );  // in the deck?

	  //swap these randomly picked cards
	      Card temp = deckOfCards[i];
	      deckOfCards[i] = deckOfCards[j];
	      deckOfCards[j] = temp;
        }
       currentCard = 0;   // Reset current card to deal
       }
     }

[toc] | [next] | [standalone]


#29506

FromRoedy Green <see_website@mindprod.com.invalid>
Date2014-08-02 01:42 -0700
Message-ID<a29pt9psbhi272puasr07jsd4jfdige7kc@4ax.com>
In reply to#29504
On Fri, 01 Aug 2014 18:16:33 -0700, Scott Dunning
<scottwd01@gmail.com> wrote, quoted or indirectly quoted someone who
said :

>Hello, I have an assignment for my summer class.  FYI, I'm super new to 
>programming in general and this is my first time with java and it's a 
>summer class so it's going super fast (please be nice!) lol.

For basic background is shuffling, see
http://mindprod.com/pseudorandom.html
-- 
Roedy Green Canadian Mind Products http://mindprod.com
The art of strongly-typed language design is largely arranging 
that errors are automatically detected as soon as possible
in the compose, compile, run cycle.

[toc] | [prev] | [next] | [standalone]


#29507

FromMartin Gregorie <martin@address-in-sig.invalid>
Date2014-08-02 10:19 +0000
Message-ID<lridvu$ic4$1@dont-email.me>
In reply to#29506
On Sat, 02 Aug 2014 01:42:13 -0700, Roedy Green wrote:

> On Fri, 01 Aug 2014 18:16:33 -0700, Scott Dunning <scottwd01@gmail.com>
> wrote, quoted or indirectly quoted someone who said :
> 
>>Hello, I have an assignment for my summer class.  FYI, I'm super new to
>>programming in general and this is my first time with java and it's a
>>summer class so it's going super fast (please be nice!) lol.
> 
> For basic background is shuffling, see
> http://mindprod.com/pseudorandom.html

In Java the indices of an array start to zero, not 1. Assuming that they 
start from 1, as you've done, will almost certainly cause problems at 
runtime by throwing "index out of range" exceptions.
 

-- 
martin@   | Martin Gregorie
gregorie. | Essex, UK
org       |

[toc] | [prev] | [next] | [standalone]


#29547

FromRoedy Green <see_website@mindprod.com.invalid>
Date2014-08-03 15:54 -0700
Message-ID<f9ftt9hc2p9jbdb92occh2pua9lasc6itd@4ax.com>
In reply to#29507
On Sat, 2 Aug 2014 10:19:42 +0000 (UTC), Martin Gregorie
<martin@address-in-sig.invalid> wrote, quoted or indirectly quoted
someone who said :

>
>In Java the indices of an array start to zero, not 1. Assuming that they 
>start from 1, as you've done, will almost certainly cause problems at 
>runtime by throwing "index out of range" exceptions.

http://mindprod.com/jgloss/pseudorandom.html

I scanned the page, but I could not find an example where your comment
applies. I showed you how to generate a random number in the bounds
low .. high, but other than that all the others start at 0.

Could you please give me the context of the error, or perhaps you were
referring to something OP or another poster said.
-- 
Roedy Green Canadian Mind Products http://mindprod.com
The art of strongly-typed language design is largely arranging 
that errors are automatically detected as soon as possible
in the compose, compile, run cycle.

[toc] | [prev] | [next] | [standalone]


#29555

FromMartin Gregorie <martin@address-in-sig.invalid>
Date2014-08-04 13:00 +0000
Message-ID<lro054$kvu$1@dont-email.me>
In reply to#29547
On Sun, 03 Aug 2014 15:54:52 -0700, Roedy Green wrote:

> On Sat, 2 Aug 2014 10:19:42 +0000 (UTC), Martin Gregorie
> <martin@address-in-sig.invalid> wrote, quoted or indirectly quoted
> someone who said :
> 
> 
>>In Java the indices of an array start to zero, not 1. Assuming that they
>>start from 1, as you've done, will almost certainly cause problems at
>>runtime by throwing "index out of range" exceptions.
> 
> http://mindprod.com/jgloss/pseudorandom.html
> 
> I scanned the page, but I could not find an example where your comment
> applies. I showed you how to generate a random number in the bounds low
> .. high, but other than that all the others start at 0.
> 
> Could you please give me the context of the error, or perhaps you were
> referring to something OP or another poster said.
>
Looking at the double loop scanning suits and card ranks (both 1-based) 
and using these ranges to control array filling made my teeth itch. OK, 
he generated the deck index separately, but it just struck me as a bad 
practice to get used to when you're using languages like C or Java with a 
fixed zero lower bound for arrays.

BTW: there's another Java flaw that nobody has yet mentioned: why is 
there a primitive array type, especially now we have generics? Surely an 
array should be an object containing the element list as well as the 
upper and lower bounds. It should also provide methods that return the 
bounds: the ability to set array bounds to suit the natural index range 
of the data in the array is very helpful for writing clear code.


-- 
martin@   | Martin Gregorie
gregorie. | Essex, UK
org       |

[toc] | [prev] | [next] | [standalone]


#29748

FromArne Vajhøj <arne@vajhoej.dk>
Date2014-08-19 17:48 -0400
Message-ID<53f3c650$0$300$14726298@news.sunsite.dk>
In reply to#29555
On 8/4/2014 9:00 AM, Martin Gregorie wrote:
> BTW: there's another Java flaw that nobody has yet mentioned: why is
> there a primitive array type, especially now we have generics? Surely an
> array should be an object containing the element list as well as the
> upper and lower bounds.

To some extent it is.

It is an object.
It contains elements.
Lower bound is always 0.
x.length-1 gives upper bound

>                        It should also provide methods that return the
> bounds: the ability to set array bounds to suit the natural index range
> of the data in the array is very helpful for writing clear code.

I agree.

Pascal/Modula-2/Ada has it.

But the idea never caught on in the C/C++/Java/C# world.

I think Java should have had it. It really helps making
the language even stronger type safe.

But too late now.

Arne

[toc] | [prev] | [next] | [standalone]


#29758

From"Chris Uppal" <chris.uppal@metagnostic.REMOVE-THIS.org>
Date2014-08-20 10:48 +0100
Message-ID<K6ydnVKqCvO_82nOnZ2dnUVZ8k2dnZ2d@bt.com>
In reply to#29748
Arne Vajhøj wrote:

> >                        It should also provide [..]
> > the ability to set array bounds to suit the natural index range
> > of the data in the array is very helpful for writing clear code.
>
> I agree.
>
> Pascal/Modula-2/Ada has it.

Didn't Wirth state that, in retrospect, it had been a mistake in Pascal ?  And 
(I thought) he'd removed it in Modula2 (or maybe it was some later iteration of 
"The Wirth Language") ?

> But the idea never caught on in the C/C++/Java/C# world.

I think the reasoning (which I agree with) is that having only one form for 
loops over an array makes off-by-one errors less likely, since there's only a 
single idiom to remember.

Of course, explicitly looping over an array is not something you usually want 
to do these days.

    -- chris 

[toc] | [prev] | [next] | [standalone]


#29925

FromArne Vajhøj <arne@vajhoej.dk>
Date2014-09-07 21:42 -0400
Message-ID<540d0972$0$291$14726298@news.sunsite.dk>
In reply to#29758
On 8/20/2014 5:48 AM, Chris Uppal wrote:
> Arne Vajhøj wrote:
>>>                         It should also provide [..]
>>> the ability to set array bounds to suit the natural index range
>>> of the data in the array is very helpful for writing clear code.
>>
>> I agree.
>>
>> Pascal/Modula-2/Ada has it.
>
> Didn't Wirth state that, in retrospect, it had been a mistake in Pascal ?  And
> (I thought) he'd removed it in Modula2

No.

>                                       (or maybe it was some later iteration of
> "The Wirth Language") ?

It was dropped in Oberon.

>> But the idea never caught on in the C/C++/Java/C# world.
>
> I think the reasoning (which I agree with) is that having only one form for
> loops over an array makes off-by-one errors less likely, since there's only a
> single idiom to remember.

I am very skeptical about a claim that using the natural indexes would
increase off-by-one errors, that goes against the philosophy in
programming language design about modelling the code as closely to
the real world as possible.

And it is certainly not true for Ada where the compiler rather
aggressively enforces type safety.

> Of course, explicitly looping over an array is not something you usually want
> to do these days.

It still happens quite often. I would tend to think that it is about
50%-50% now. There are simply too many cases where for each concept
is not suited.

Arne

[toc] | [prev] | [next] | [standalone]


#29928

FromEric Sosman <esosman@comcast-dot-net.invalid>
Date2014-09-07 22:04 -0400
Message-ID<luj2rl$lth$1@dont-email.me>
In reply to#29758
On 8/20/2014 5:48 AM, Chris Uppal wrote:
>[...]
> Of course, explicitly looping over an array is not something you usually want
> to do these days.

     ???!

     When was the array deprecated?

     When was iteration over an array's elements deprecated?

     When were arrays with more "slots" than "active elements"
deprecated?

     When did we all go stark raving MAD?????

-- 
esosman@comcast-dot-net.invalid

[toc] | [prev] | [next] | [standalone]


#29929

FromArne Vajhøj <arne@vajhoej.dk>
Date2014-09-07 22:08 -0400
Message-ID<540d0f95$0$298$14726298@news.sunsite.dk>
In reply to#29928
On 9/7/2014 10:04 PM, Eric Sosman wrote:
> On 8/20/2014 5:48 AM, Chris Uppal wrote:
>> [...]
>> Of course, explicitly looping over an array is not something you
>> usually want
>> to do these days.
>
>      ???!
>
>      When was the array deprecated?
>
>      When was iteration over an array's elements deprecated?
>
>      When were arrays with more "slots" than "active elements"
> deprecated?
>
>      When did we all go stark raving MAD?????

I will not rule out that we are all stark raving mad.

:-)

But traditional for loop to go through arrays is not deprecated.

If one only need to read the elements *and* one need to read all
elements *and* one does not need to know the index, then a new
for loop is probably better.

But that was a whole bunch of if's. Which are not always true.

Arne


[toc] | [prev] | [next] | [standalone]


#29514

FromMike Amling <mamling@chaff.us>
Date2014-08-03 07:38 -0500
Message-ID<c46opoF6ekvU1@mid.individual.net>
In reply to#29504
On 8/1/14 8:16 PM, Scott Dunning wrote:
> Hello, I have an assignment for my summer class.  FYI, I'm super new to
> programming in general and this is my first time with java and it's a
> summer class so it's going super fast (please be nice!) lol.
>
> Basically I started writing my code in one class, then I split it up
> into a Card class and a DeckOfCards class and I now need to figure out
> how to get it all to work together.  I get a little confused with
> calling methods sometimes, especially when separate classes are in play.
>   I think I just need a method to deal out five cards that also tells
> how many cards are left in the deck.  Then get it all working together
> correctly.  Also, I need a toString method but I honestly do not know
> how to go about that.  Any help is greatly appreciated!  If you could
> help explain things too that would be awesome!  I think I have
> everything SO FAR correct but I could be wrong and I'm sure there are
> better ways to write the code, I'll take any suggestions for a cleaner
> look too.  FYI, I think the prof would rather arrays then enums since
> we're dealing with arrays right now.
>
> Here are the directions...
> Design and implement a class called Card that represents a standard
> playing card. Each card has a suit and a face value. Then create a class
> called DeckOfCards that stores 52 objects of the Card class. Include
> methods to shuffle the deck, deal a card and report the number of cards
> left in the deck. The shuffle methods should assume a full deck. Create
> a driver class (CardsGame) with a main method that deals five cards from
> the shuffled deck, printing each card as it is dealt. Make sure to write
> the appropriate constructors, getters, setters, toString and other
> methods as required for both classes.
>
>
> The main class, CardsGame Class
>
>      import java.util.Scanner;
>
>      public class CardsGame {
>          public static void main (String [] args) {
>
>         }
>      }
>
> Card Class
>
>      class Card {
>         public static final int SPADE   = 4;
>         public static final int HEART   = 3;
>         public static final int CLUB    = 2;
>         public static final int DIAMOND = 1;
>
>         private int rank;
>         private int suit;
>         private static final String[] Suit = {"Hearts", "Clubs",
> "Spades", "Diamonds"};
>         private static final String[] Rank = {"Ace", "2", "3", "4", "5",
> "6", "7", "8", "9", "10", "Jack", "Queen", "King"};
>
>         private int cardSuit;
>         private int cardRank;
>
>         public Card(int suit, int rank) {
   Better to throw an exception if suit or rank is outside their 
required range than to allow malformed instances.
>            if (rank == 1)
>               cardRank = 14;     // Give Ace the rank 14
>            else
>               cardRank = (int) rank;
>               cardSuit = (int) suit;
   Indentation does not match conditional execution.
>         }
>
>         public int suit() {
>            return this.cardSuit;
>         }
>
>         public String suitStr() {
>            return(this.Suit[ this.cardSuit ]);
>         }
>
>         public int rank() {
>            return this.cardRank;
>         }
>
>         public String rankStr() {
>            return ( Rank[ cardRank ] );
>         }
>
>
>         public String toString() {
>            return ( Rank[ cardRank ] + Suit[ cardSuit ] );
>         }
>      }
>
> DeckOfCards Class
>
>      class DeckOfCards {
>         public static final int NEWCARDS = 52;
   I suggest
           private static final Random CHANCE=new Random();
>         private Card[] deckOfCards;         // Contains all 52 cards
>         private int currentCard;            // deal THIS card in deck
>
>      public DeckOfCards( ) {
>        deckOfCards = new Card[NEWCARDS];
>        int i = 0;
>
>        for ( int suit = Card.DIAMOND; suit <= Card.SPADE; suit++ )
>           for ( int rank = 1; rank <= 13; rank++ )
>               deckOfCards[i++] = new Card(suit, rank);
>               currentCard = 0;
   Indented as if it were part of the for loop.
   I suggest using the braces for each and every if, else, for, while 
and do. You'll never regret it.
>       }
>
>
>         //shuffle(n): shuffle the deck
>         public void shuffle(int n) {
   Search for Fisher-Yates shuffling algorithm (sometimes misattributed 
to Knuth). There's no need for shuffle to have a parameter if it's 
intended to perform a random shuffle.
>            int i, j, k;
>            for ( k = 0; k < n; k++ ) {
>                i = (int) ( NEWCARDS * Math.random() );  // Pick 2 random
> cards
    java.util.Random is better for random integers. CHANCE.nextInt(n) 
returns a random integer in the range 0 .. n-1, which is what you'll want.
>                j = (int) ( NEWCARDS * Math.random() );  // in the deck?
>
>        //swap these randomly picked cards
>            Card temp = deckOfCards[i];
>            deckOfCards[i] = deckOfCards[j];
>            deckOfCards[j] = temp;
>         }
>        currentCard = 0;   // Reset current card to deal
>        }
   Don't you need something like
     Card deal() {
       if (currentCard==NEWCARDS) {
         throw IllegalStateException("All gone.");
       }
       return deckOfCards[currentCard++];
     }
>      }

[toc] | [prev] | [next] | [standalone]


#29515

FromEric Sosman <esosman@comcast-dot-net.invalid>
Date2014-08-03 10:23 -0400
Message-ID<lrlgl1$k2k$1@dont-email.me>
In reply to#29504
On 8/1/2014 9:16 PM, Scott Dunning wrote:
> [...]
>         //shuffle(n): shuffle the deck
>         public void shuffle(int n) {
>            int i, j, k;
>            for ( k = 0; k < n; k++ ) {
>                i = (int) ( NEWCARDS * Math.random() );  // Pick 2 random
> cards
>                j = (int) ( NEWCARDS * Math.random() );  // in the deck?
>
>        //swap these randomly picked cards
>            Card temp = deckOfCards[i];
>            deckOfCards[i] = deckOfCards[j];
>            deckOfCards[j] = temp;
>         }
>        currentCard = 0;   // Reset current card to deal
>        }
>      }

     Others have observed that this shuffling procedure is biased,
and suggested alternatives.  I'd just like to point out that it
may not be necessary to shuffle at all!

     Here's the idea: The fundamental operation is "deal one card"
(you can do this N times in succession to deal N cards).  Judging
by your `currentCard' variable, you plan to shuffle the deck and
then march through it in sequence, dealing the first, second, ...
card in succession.  That will work fine (if you shuffle well).

     But what if you just left the deck in any old order at all,
even "factory-fresh" with all the suits and ranks in order, *but*
instead of dealing sequentially you dealt a randomly-chosen card?
You'd need to ensure that a card already dealt wouldn't be dealt
again (in the Wild West, the presence of two Aces of Spades in a
single poker game might well provoke a gunfight), so after dealing
the randomly-chosen card you'd need to remove it from the deck.
That's a fairly natural idea, though: If you start with a deck of
fifty-two cards and deal one of them, you expect to be holding a
deck of fifty-one, right?

     Okay, so this suggests not a `currentCard' variable that
marches through a shuffled array, but a `cardCount' variable
that keeps track of how many un-dealt cards remain.  In a fresh
deck this variable would be 52, and it would decrease as cards
were plucked out and dealt away.  Here's an outline:

	public class DeckOfCards {
	    private final Card[] cards;
	    private int cardCount;

	    public DeckOfCards() {
	        cards = new Card[52];
	        // ... fill the array with Cards ...
	        cardCount = 52;
	    }

	    public Card dealOneCard() {
	        // Sanity check:
	        if (cardCount <= 0) {
	            throw new IllegalStateException("no cards left!");
	        }

	        // Choose the card to deal:
	        int which = (int) (cardCount * Math.random());
	        Card dealt = cards[which];

	        // Remove the dealt card from the deck by moving
	        // the last card into the vacated place (this works
	        // even when dealing the last card):
	        cards[which] = cards[cardCount - 1];

	        // There's one less card than there used to be:
	        --cardCount;

	        return dealt;
	    }

	    // ... other methods ...
	}

(I've written this for clarity; there are ways to tighten it up a
little, and Mike Amling has suggested a better way to get a random
integer, but I've tried to stick with things you've already shown
you're familiar with.)

     Your assignment says you're supposed to write a shuffle() method,
and perhaps your instructor will give you poor marks if you don't.
But then you might pacify him with

	public void shuffle() {
	    if (cardCount != 52) {
	        throw new IllegalStateException(
	            "not playing with a full deck (as promised)!");
	    }
	}

If he objects that the method is vacuous, your comeback could be
that *by using the other methods of DeckOfCards* there's no way
to detect the vacuousness!  He can create as many decks and deal
as many cards as he likes and subject them to every statistical
test at his disposal, and although he might uncover problems with
Math.random() and so on he will never be able to show that you're
not shuffling!

     ... and *that* is another important aspect of programming,
called "encapsulation."  The idea is that a class promises to
provide various behaviors but does not promise to do so in any
particular way.  You describe *what* the (exposed) methods of
your class will do, but you don't say *how* they'll do it.  This
means that next week when you think of a better way (like, how
to deal a random card without shuffling), you're free to change
how you've done things.  A short-order cook filling two orders
for scrambled eggs needn't reveal whether he cooked two small
batches or one big one; all he needs to do is serve up two platefuls
by whatever means he finds convenient.  If your classes follow a
similar philosophy, you'll write better classes.

-- 
esosman@comcast-dot-net.invalid

[toc] | [prev] | [next] | [standalone]


#29525

Fromlipska the kat <lipskathekat@example.com>
Date2014-08-03 18:52 +0100
Message-ID<DfadnfW996dp60POnZ2dnUVZ7q2dnZ2d@bt.com>
In reply to#29515
On 03/08/14 15:23, Eric Sosman wrote:
> On 8/1/2014 9:16 PM, Scott Dunning wrote:

<snip>

>      Others have observed that this shuffling procedure is biased,
> and suggested alternatives.  I'd just like to point out that it
> may not be necessary to shuffle at all!
>
>      Here's the idea: The fundamental operation is "deal one card"
> (you can do this N times in succession to deal N cards).  Judging
> by your `currentCard' variable, you plan to shuffle the deck and
> then march through it in sequence, dealing the first, second, ...
> card in succession.  That will work fine (if you shuffle well).
>
>      But what if you just left the deck in any old order at all,
> even "factory-fresh" with all the suits and ranks in order, *but*
> instead of dealing sequentially you dealt a randomly-chosen card?

<snip>

This is a poor abstraction I'm afraid. One of the things we try to teach 
when we teach an OO language is the concept of the real world abstraction.

In the real world, if you dealt a 'randomly chosen card' your 
opponent[s] might be forgiven for `popping a cap in yo' ass` :-)

Not only is a shuffle method required by the specification but it is a 
realistic real world abstraction, also it removes any additional 
complexity involved in keeping track of which cards have been dealt. I 
believe that if you do this in 'Vegas (card counting that is) you will 
be politely shown the door by a number of large European gentlemen with 
a penchant for olive oil.


<snip>


-- 
lipska the kat - treacherous feline.
Proudly nominated for IPOTY 2014 - LIGAF
GNU/Linux user #560883 - linuxcounter.net

[toc] | [prev] | [next] | [standalone]


#29527

FromJeff Higgins <jeff@invalid.invalid>
Date2014-08-03 14:16 -0400
Message-ID<lrlu9q$o7d$1@dont-email.me>
In reply to#29525
On 08/03/2014 01:52 PM, lipska the kat upchucked.

Congratulations.
Absolutely Racialicious.

[toc] | [prev] | [next] | [standalone]


#29528

Fromlipska the kat <lipskathekat@example.com>
Date2014-08-03 19:21 +0100
Message-ID<da2dnRL2q5gS4EPOnZ2dnUVZ7tSdnZ2d@bt.com>
In reply to#29527
On 03/08/14 19:16, Jeff Higgins wrote:
> On 08/03/2014 01:52 PM, lipska the kat upchucked.
>
> Congratulations.
> Absolutely Racialicious.
>

What are you suggesting ?

-- 
lipska the kat - treacherous feline.
Proudly nominated for IPOTY 2014 - LIGAF
GNU/Linux user #560883 - linuxcounter.net

[toc] | [prev] | [next] | [standalone]


#29529

FromJeff Higgins <jeff@invalid.invalid>
Date2014-08-03 14:38 -0400
Message-ID<lrlviv$2e3$1@dont-email.me>
In reply to#29528
On 08/03/2014 02:21 PM, lipska the kat wrote:
> On 03/08/14 19:16, Jeff Higgins wrote:
>> On 08/03/2014 01:52 PM, lipska the kat upchucked.
>>
>> Congratulations.
>> Absolutely Racialicious.
>>
>
Your sentence seems out of character.
> What are you suggesting ?
                          ^^
                          , hmm

[toc] | [prev] | [next] | [standalone]


#29530

Fromlipska the kat <lipskathekat@example.com>
Date2014-08-03 19:41 +0100
Message-ID<q6KdncIaqePEH0POnZ2dnUVZ8i2dnZ2d@bt.com>
In reply to#29529
On 03/08/14 19:38, Jeff Higgins wrote:
> On 08/03/2014 02:21 PM, lipska the kat wrote:
>> On 03/08/14 19:16, Jeff Higgins wrote:
>>> On 08/03/2014 01:52 PM, lipska the kat upchucked.
>>>
>>> Congratulations.
>>> Absolutely Racialicious.
>>>
>>
> Your sentence seems out of character.
>> What are you suggesting ?
>                           ^^
>                           , hmm
>

It's called a question mark.

http://en.wikipedia.org/wiki/Question_mark

oh, wait a minute ...

-- 
lipska the kat - treacherous feline.
Proudly nominated for IPOTY 2014 - LIGAF
GNU/Linux user #560883 - linuxcounter.net

[toc] | [prev] | [next] | [standalone]


#29540

FromMike Amling <mamling@chaff.us>
Date2014-08-03 16:05 -0500
Message-ID<c47mfmFcmk9U1@mid.individual.net>
In reply to#29515
On 8/3/14 9:23 AM, Eric Sosman wrote:
>      public class DeckOfCards {
>          private final Card[] cards;
>          private int cardCount;
>
>          public DeckOfCards() {
>              cards = new Card[52];
>              // ... fill the array with Cards ...
>              cardCount = 52;
>          }
>
>          public Card dealOneCard() {
>              // Sanity check:
>              if (cardCount <= 0) {
>                  throw new IllegalStateException("no cards left!");
>              }
>
>              // Choose the card to deal:
>              int which = (int) (cardCount * Math.random());
>              Card dealt = cards[which];
>
>              // Remove the dealt card from the deck by moving
>              // the last card into the vacated place (this works
>              // even when dealing the last card):
>              cards[which] = cards[cardCount - 1];
>
>              // There's one less card than there used to be:
>              --cardCount;
>
>              return dealt;
>          }
>
>          // ... other methods ...
>      }

   So, the shuffle method is superfluous. Rather than myDeck.shuffle(), 
one would code myDeck=new DeckOfCards()? Not bad.

--Mike Amling
R2VuZXJhbGl6YWJsZSB0byBkcmF3aW5nIGZyb20gdXJucy4=

[toc] | [prev] | [next] | [standalone]


#29517

FromJeff Higgins <jeff@invalid.invalid>
Date2014-08-03 11:08 -0400
Message-ID<lrlj8k$6fc$1@dont-email.me>
In reply to#29504
On 08/01/2014 09:16 PM, Scott Dunning wrote:
> Hello, I have an assignment for my summer class.  FYI, I'm super new to
> programming in general and this is my first time with java and it's a
> summer class so it's going super fast (please be nice!) lol.

No. It seems to be going slowly. The last three assignments you've
brought here are rehashes. Surely by now you should have gone into
interfaces and collections.

Your Card class will be more easily used if it implement the
java.lang.Comparable<T> interface

> Basically I started writing my code in one class, then I split it up
> into a Card class and a DeckOfCards class and I now need to figure out
> how to get it all to work together.  I get a little confused with
> calling methods sometimes, especially when separate classes are in play.

PLEASE work your way through the "Learning the Java Language" trail in
the Java Tutorials. Your instructor is not helping you if he hasn't
insisted upon this.

>   I think I just need a method to deal out five cards that also tells
> how many cards are left in the deck.

Not necessarily. java.lang.Iterable<T> interface comes to mind.
As others have pointed out: there are many ways to accomplish
an outcome.

> Then get it all working together
> correctly.  Also, I need a toString method but I honestly do not know
> how to go about that.  Any help is greatly appreciated!  If you could
> help explain things too that would be awesome!

For what? Your Card class? What are its attributes? Take out your paper
and pencil, or even just put on your thinking cap and decide how you
want your Card represented as a String.
<http://unicode.org/charts/PDF/U1F0A0.pdf>
You already have a toString method, but it is probably not what you want.
<http://docs.oracle.com/javase/tutorial/java/IandI/objectclass.html>
Rank[ cardRank ] + Suit[ cardSuit ] would present a fairly ugly
representation, have you tried it?

> I think I have
> everything SO FAR correct but I could be wrong and I'm sure there are
> better ways to write the code, I'll take any suggestions for a cleaner
> look too.  FYI, I think the prof would rather arrays then enums since
> we're dealing with arrays right now.

I'm gaining less respect, especially if the following is verbatim.

> Here are the directions...
> Design and implement a class called Card that represents a standard
> playing card. Each card has a suit and a face value. Then create a class
> called DeckOfCards that stores 52 objects of the Card class. Include
> methods to shuffle the deck, deal a card and report the number of cards
> left in the deck. The shuffle methods should assume a full deck. Create
> a driver class (CardsGame) with a main method that deals five cards from
> the shuffled deck, printing each card as it is dealt. Make sure to write
> the appropriate constructors, getters, setters, toString and other
> methods as required for both classes.

Why show us a place holder?

> The main class, CardsGame Class
>
>      import java.util.Scanner;
>
>      public class CardsGame {
>          public static void main (String [] args) {
>
>         }
>      }
>

[toc] | [prev] | [next] | [standalone]


#29519

FromEric Sosman <esosman@comcast-dot-net.invalid>
Date2014-08-03 11:41 -0400
Message-ID<lrll78$jtc$1@dont-email.me>
In reply to#29517
On 8/3/2014 11:08 AM, Jeff Higgins wrote:
> On 08/01/2014 09:16 PM, Scott Dunning wrote:
>> Hello, I have an assignment for my summer class.  FYI, I'm super new to
>> programming in general and this is my first time with java and it's a
>> summer class so it's going super fast (please be nice!) lol.
>
> No. It seems to be going slowly. The last three assignments you've
> brought here are rehashes. Surely by now you should have gone into
> interfaces and collections.
>
> Your Card class will be more easily used if it implement the
> java.lang.Comparable<T> interface

     I'd advise against this, because the ordering depends not on the
Card, but on the rules of whatever game is being played.  There are
games where Ace is high, games where it is low, games where it can
be either at the discretion of the player, and for all I know there
may be games where Ace can lie between King and Deuce.  And then
there's the question of suit: How does the Seven of Hearts compare
to the Jack of Clubs? Would knowing whether Hearts are trumps affect
your answer?

     Scott: Don't Go There; you'll just get lost.

-- 
esosman@comcast-dot-net.invalid

[toc] | [prev] | [next] | [standalone]


Page 1 of 3  [1] 2 3  Next page →

Back to top | Article view | comp.lang.java.programmer


csiph-web