简体   繁体   English

如何减少代码中的重复性?

[英]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. 我看到第一个if()块,即(cards == 1),有点重复。 I don't want to do 4 if blocks to do the whole deck. 我不想做4块积木做整个套牌。

My questions to you are as follows, 1. how would I go about reducing the code in that way? 我对你的问题如下:1。我将如何以这种方式减少代码? 2. Is it possible? 2.有可能吗? Or 3. is it just best to do 4 sets of if() blocks for each suit? 或3.最好为每件套装做4套if()块?

Thanks in advance for the help! 先谢谢您的帮助!

private String[] cards = { "Ace", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King"};
private String[] colors = {"Clubs", "Spades", "Hearts", "Diamonds"};

Then iterate through both array using for loops. 然后使用for循环遍历两个数组。

for (int iColor = 0; iColor < colors.length; iColor++) {
    for (int iCard = 0; iCard < cards.length; iCard++) {
        System.out.printf("%s of %s%n", cards[iCard], colors[iColor];
    }
}

If the only problem you have is printing the suit, then I would either create an array: 如果您遇到的唯一问题是打印套装,那么我会创建一个数组:

String[] suits = {"Clubs", "Spades", "Hearts", "Diamonds"};

or an ArrayList<String>() : 或者ArrayList<String>()

ArrayList<String> suits = new ArrayList<String>();
suits.add("Clubs");
suits.add("Spades");
suits.add("Hearts");
suits.add("Diamonds");

You can simply iterate it like that: 你可以简单地迭代它:

for(String suit : suits)

make array of it: make数组:
String[] arr = new String[]{"clubs","spades","hearts","diamonds"}
then use loop: 然后使用循环:
for(int i=0;i<arr.length;i++){} example: for(int i=0;i<arr.length;i++){}示例:

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

Create a method printSuit(String suitName) and use it inside each if statement. 创建一个方法printSuit(String suitName)并在每个if语句中使用它。

You can also create Enum of suits and iterate over its values. 您还可以创建套装的Enum并迭代其值。

For algorithm understanding purpose : 出于算法理解的目的:

If you have a For with X values and inside a if for each values, than just remove the for and the if . 如果你有一个For with X值,并且if里面有一个值,那么只需删除forif

for (int cards = 1; cards <= 4; cards++){
       if (cards == 1) System.out.println("A");
       if (cards == 2) System.out.println("B");
       if (cards == 3) System.out.println("C");
       if (cards == 4) System.out.println("D");
}

is exactly the same as : 与以下内容完全相同:

System.out.println("A");
System.out.println("B");
System.out.println("C");
System.out.println("D");

To use enum would be best in your case with extra function. 在你的情况下,使用enum最好具有额外的功能。
Here is my aproach to make your code simple. 这是我的方法,使你的代码变得简单。

public static void main(String...args){
    for(Card card : Card.values()){
        showCards(card);
    }
}
static void showCards(Card card){
    for(CardVal cv : CardVal.values()){
        System.out.println(cv + " of "+card);
    }
}
static enum Card {
    Club, 
    Spades,
    Hearts,
    Diamond
}
static enum CardVal {
    Ace,
    Two,
    Three,
    Four,
    Five,
    Six,
    Seven,
    Eight,
    Nine,
    Ten,
    Jack,
    Queen,
    King
}

A more object-oriented solution would be to create a Card class, and promote suit and value to enumerated types as such: 更面向对象的解决方案是创建一个Card类,并将枚举类型的套装和值提升为:

public class Card {

    public enum Suit {
        HEARTS,
        CLUBS,
        SPADES,
        DIAMONDS;
    }

    public enum FaceValue {
    ACE,
    KING,
    QUEEN,
    JACK,
    TEN,
    NINE,
    EIGHT,
    SEVEN,
    SIX,
    FIVE,
    FOUR,
    THREE,
    TWO,
    ONE
    }

    private Suit suit;
    private FaceValue value;

    public Card(Suit suit, FaceValue value) {
        this.suit = suit;
        this.value = value;
    }

    @Override
    public String toString() {
        return value.toString() + " of " + suit.toString();
    }

}

Then you can reduce your printing code to two nested loops: 然后,您可以将打印代码减少到两个嵌套循环:

public static void main(String[] args) {

    for(Suit s : Suit.values()) {
        for (FaceValue v : FaceValue.values()) {
            System.out.println(new Card(s,v));
        }
    }
}

As java is object oriented language, try to think objects 由于java是面向对象的语言,因此尝试思考对象

first create Enums with colours and ranks; 首先创建具有颜色和排名的枚举;

    enum Colour{
        Clubs,Diamonds,Hearts,Spades;
    }

    enum Rank{
         Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King,Ace
    }

Define your card 定义你的卡

class Card{
    @Override
    public String toString() {
        return rank + " of "+colour;
    }
    public Card(Colour colour, Rank rank) {
        super();
        this.colour = colour;
        this.rank = rank;
    }
    private final Colour colour;
    private final Rank rank;

}

it will be good if your card will implements comparable interface, then if you try to create any card game it might be useful 如果你的卡会实现类似的界面,那将是很好的,那么如果你尝试创建任何纸牌游戏它可能是有用的

and last what you need is deck 最后你需要的是甲板

class Deck{
    List<Card> cards = new ArrayList<Card>();       
    public Deck(){
        for (Colour colour : Colour.values()){
            for (Rank rank : Rank.values()){
                cards.add(new Card(colour, rank));
            }   
        }
    }
}

deck when instantiated creates all cards, it can be usefull to manipulate cards 当实例化甲板创建所有卡片时,它可以用来操纵卡片

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM