Search code examples
javaappletjapplet

How can I reduce the repetiveness in my code?


Look at the following program:

public class HouseOfCards 
{
    public static void main(String[] args)
    {
        for (int cards = 1; cards <= 4; cards++)
        {
           if (cards == 1) 
           {
               System.out.println("Ace of Clubs");
                for (int singles = 2; singles <= 9; singles++)
                { 
                   System.out.println(singles + " of Clubs");
                }//end of for loop()
               System.out.println("Jack of Clubs");
               System.out.println("Queen of Clubs");
               System.out.println("King of Clubs");
               System.out.println("Ace of Clubs");
          }//end of if() 
                            ......
             //More else if() blocks for each suit
                            ......
        }//end of for loop()
     }//end of method main() 
   }//end of class HouseOfCards

In the above code, I want to print the first set of cards, that being clubs, then do the same for the rest of the suits in a "new deck order" format.

Clubs --> Spades --> Hearts --> Diamonds

I see that the first if() block, that being, (cards == 1), is a little repetitive. I don't want to do 4 if blocks to do the whole deck.

My questions to you are as follows, 1. how would I go about reducing the code in that way? 2. Is it possible? Or 3. is it just best to do 4 sets of if() blocks for each suit?

Thanks in advance for the help!


Solution

  • make array of it:
    String[] arr = new String[]{"clubs","spades","hearts","diamonds"}
    then use loop:
    for(int i=0;i<arr.length;i++){} example:

    public class HouseOfCards 
    {
        private static final String[] arr = new String[]{"Clubs","Spades","Hearts","Diamonds"};
        public static void main(String[] args)
        {
                for(int i=0;i<arr.length;i++)
                {
                System.out.println("Ace of "+arr[i]);
                    for (int singles = 2; singles <= 9; singles++)
                    { 
                       System.out.println(singles + " of "+arr[i]);
                    }//end of for loop()
                   System.out.println("Jack of "+arr[i]);
                   System.out.println("Queen of "+arr[i]);
                   System.out.println("King of "+arr[i]);
                   System.out.println("Ace of "+arr[i]);
               }//end of if()
         }//end of method main() 
       }//end of class HouseOfCards