Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 6 of 6

Thread: Creating a series of objects with incrementing names

  1. #1
    Member
    Join Date
    Jul 2013
    Posts
    47
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Creating a series of objects with incrementing names

    Let me see if I can explain this right. I have this program (same as from my last thread) to create 52 objects that represent playing cards. I am using a for() loop to run over the object creation 52 times, thus creating 52 cards, but I don't want to have to name each one (indeed, that wouldn't even work in a for() loop).

    How can I increment the card's names? For instance, first object is Card1, then Card2, Card3, Card4 and so forth?

    Also, a little secondary question:

    class Card {
     
      private static String[][] type = {
          {"clubs", "diamonds", "hearts", "spades"},
              {"ace", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "jack",
              "queen", "king"}
      };
     
      private String suit, rank;
      private static final int suitCall1 = 0;
      private static int suitCall2 = 0;
      private static final int rankCall1 = 1;
      private static int rankCall2 = 0;
     
            public Card() {
                if(rankCall2 == 12) {
                    suitCall2++;
                }
                suit = type[suitCall1][suitCall2];
                rank = type[rankCall1][rankCall2++];
     
    }
     
    }

    As you can see, there wouldn't actually be a problem only running this code 52 times, but if it ran a 53rd time, there would (I assume) be a compiler error because suitCall2 could not be incremented again due to going out of range of the array. I'm going to guess this is where exception handling comes in? If so, don't bother answering because that comes up in a later lesson and I don't want to confuse myself lol.

    Thanks,
    -s45


  2. #2
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    6,310
    My Mood
    Mellow
    Thanks
    253
    Thanked 780 Times in 765 Posts

    Default Re: Creating a series of objects with incrementing names

    You have some ideas jumbled up, and your question isn't clear. I'm not really sure what you're asking when you wander off into 53 versus 52 cards.

    The 52 Card objects represent a deck, and the creation of a Deck does not belong in the Card class. Cards should know nothing about Decks. The Deck class (or however the deck is created) decides how many Card objects there are in a Deck object, creates the card objects with that number of distinct characteristics, like 4 suits of 13 ranks. Following that design, a card should include the fields 'suit' and 'rank' and not have a 'name'. Frankly, if you renamed what you posted Deck and modified it slightly as shown below, you'd be closer. (Why did you have an 'ace' and a '1'?)
    // class Deck creates a standard deck of 52 cards of 4 suits of 13 ranks each
    class Deck
    {
    	private static String[] suit = {"clubs", "diamonds", "hearts", "spades"};
    	private static String[] rank = {"ace", "2", "3", "4", "5", "6", "7",
    		"8", "9", "10", "jack", "queen", "king"};
     
    	Card[] cards;
     
    	// default constructor
    	public Deck()
    	{
    		cards = new Card[suit.length * rank.length];
     
    		for ( int i = 0 ; i < suit.length ; i++ )
    		{
    			for ( int j = 0 ; j < rank.length ; j++ )
    			{
    				cards[suit.length * i + j] = new Card( suit[i], rank[j] );
    			}
    		}
     
    	} // end default constructor Deck()
     
    	// other Deck methods as needed . . .
     
    } // end class Deck

  3. #3
    Member
    Join Date
    Jul 2013
    Posts
    47
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Creating a series of objects with incrementing names

    Wow... that's a good approach, lol. Here's the thing: The code you posted isn't hard to understand, but I wonder if you have advice for me on how one should THINK as a programmer to have stuff like that come so easily? I mean especially this nested for() loop and the cards[suit.length * i + j] algorithm - if you follow the code, that works out exactly so that cards[] will step up each time. But how did you think to do that? I'm not sure how to frame this question right, and maybe I'm just not mathematically minded enough, but - it looks to me like you knew automatically that multiplying the number of suits by the current suit and adding the current rank would increment cards[] correctly in the code. But for me, if I had ever thought to write that, it would have only gotten that way because I had figured out that that operation would produce the right number result, rather than just knowing it off hand. Do you get what I'm asking?

    Maybe it's a stupid or even weird question - I just want to understand how to think to be able to have these solutions come so easily. Not just the cards[] algorithm but even the nested for() loops. I'm not sure how long it would have taken me to think of doing either.

    -s45

    EDIT: Well, after thinking a bit more about cards[suit.length * i + j] I understand the math concept now, but I still think I need to learn how to think like a programmer better.

  4. #4
    Super Moderator jps's Avatar
    Join Date
    Jul 2012
    Posts
    2,642
    My Mood
    Daring
    Thanks
    90
    Thanked 263 Times in 232 Posts

    Default Re: Creating a series of objects with incrementing names

    Quote Originally Posted by summit45 View Post
    how one should THINK as a programmer to have stuff like that come so easily?
    Practice problem solving often.

    Quote Originally Posted by summit45 View Post
    mathematically minded
    Math is a big part of it.

    Quote Originally Posted by summit45 View Post
    multiplying the number of suits by the current suit and adding the current rank would increment cards[] correctly
    The same math will be used frequently acting on arrays. More practice will reveal this as a common pattern

  5. #5
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    6,310
    My Mood
    Mellow
    Thanks
    253
    Thanked 780 Times in 765 Posts

    Default Re: Creating a series of objects with incrementing names

    I find math easy, always have, so I can't pretend to see the problem from a perspective that finds math challenging, foreign, or scary. Even so, I wasn't born knowing these common programming patterns, so I learned them just like you will. Ask questions, read other people's code, and then practice, practice, practice, . . ., practice applying what you find interesting and want to learn until it just flows. It can happen, but it comes from your curiosity, desire to learn, and then nearly endless practice as is required to master any skill, unless you're a prodigy or savant.

  6. #6
    Member
    Join Date
    Jul 2013
    Posts
    47
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Creating a series of objects with incrementing names

    Yaay, my code words now. It all came to me last night/this morning. It's amazing how programming does that. I just don't get it, then later, I do, lol. But anyway here it is. By the way Greg, I appreciate your suggestion about a Deck class. That will actually help me a lot with the next exercise in the lesson, but this one was just about creating a Card class. Creating a "deck" and writing it to std/out was just my idea to test the code.

    package cardsexercise;
     
    class Card {
     
      private static String[] suits = {"Clubs", "Diamonds", "Hearts", "Spades"};
     
     
    private static String[] ranks = {"Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack",
              "Queen", "King"};
     
    //Following two int vars will monitor position in the array and increment
    //the card being created.
      private static int suitCall = 0;
      private static int rankCall = 0;
      private String suit, rank;
     
      public Card() { //First check if the suit needs to be advanced.
          if(rankCall == ranks.length) {
              rankCall = 0;
              suitCall++;
          }
          suit = suits[suitCall];
          rank = ranks[rankCall++];
     
    }
     
      public static int getTotalCards() {
          return suits.length * ranks.length;
    }
     
      public String getSuit() {
          return suit;
      }
    public String getRank() {
        return rank;
    }
    }
     
    public class CardsExercise {
     
     
        public static void main(String[] args) {
     
        int numCards = Card.getTotalCards();
        Card[] cards;
        cards = new Card[numCards]; //Create a Card array of a length equal
                                    //to the total possible number of cards.
     
            for(int i = 0; i < numCards; i++) { //Fill the card array.
     
                cards[i] = new Card();
            }
     
            for(int i = 0; i < cards.length; i++) {
                int h = i; //Buffer var to shield i from the incrementation by j.
                int j = ++h;
                String k = cards[i].getSuit();
                String n = cards[i].getRank();
                System.out.println("Card " + j + ": " + n + " of " + k);
     
            }
     
    }
    }

    -s45

Similar Threads

  1. [SOLVED] Creating an array of objects
    By Benner in forum What's Wrong With My Code?
    Replies: 1
    Last Post: March 22nd, 2013, 04:00 AM
  2. Creating Objects at specified indexes
    By dougie1809 in forum Object Oriented Programming
    Replies: 4
    Last Post: March 1st, 2013, 08:20 PM
  3. Creating random objects
    By JackCannon15 in forum Object Oriented Programming
    Replies: 2
    Last Post: November 18th, 2011, 08:50 AM
  4. Problem with automatically creating new objects with unique names
    By oniamien in forum Java Theory & Questions
    Replies: 2
    Last Post: December 4th, 2010, 02:38 PM
  5. Loop not creating objects
    By xecure in forum What's Wrong With My Code?
    Replies: 2
    Last Post: October 30th, 2010, 11:48 PM