Search code examples
javaarraysobjectplaying-cards

Creating a Deck of Cards


I'm can't seem to figure out how to create this simple deck of cards. If somebody could please show an example of what would go into the "your code goes here" section, it would be very helpful.

By entering suitable code in place of the comment in the following main method, create a deck of cards:

public class Card 
  { 
    private String mySuit; 
    private int myValue; 

    public Card( String suit, int value ) 
    { 
      mySuit = suit; 
      myValue = value; 
    } 

    public String name() 
    { 
      String[] cardNames =  
        { 
          "Deuce", "Three", "Four", "Five", 
          "Six", "Seven", "Eight", "Nine", "Ten", 
          "Jack", "Queen", "King", "Ace" 
        }; 

      return cardNames[ myValue - 2 ] + " of " + mySuit; 
    } 
  } 

  public class MainClass 
  { 
    public static void main( String[] args ) 
    { 
      Card[] deck = new Card[ 52 ]; 
      String[] suits = { "spades", "hearts", "diamonds", "clubs"  }; 

      int i; 
      for ( i = 0 ; i < suits.length ; i++ )
      {
        for ( int k = 2 ; k <= 14 ; k++ ) 
        {
          // your code goes here

        }
      }  

      for ( Card card : deck ) 
        System.out.println( card.name() ); 
    } 
  }    

Solution

  • I don't have the time to test this, but what's intended is something like:

    deck[13 * i + k - 2] = new Card(suits[i], k);
    

    though personally I would use integers for suits as well--just a waste of time and space to use strings.