在甲板上找到最高价值的卡

时间:2016-01-10 17:02:05

标签: java

在Java程序中,我试图返回卡片中最大的价值卡。

钻石是价值最低的套装。然后俱乐部,然后心脏和最后的黑桃有最大的价值。正如您所看到的,我在findLargest方法中有一段代码只是简单地说largest =。我不知道这个方法的其余部分应该去哪里。

public class Card {

    private int number;
    private String suit;

    /*
     * Randomly creates a card numbered 1 to 13 (ace = 1!) and labelled "Hearts","Clubs","Diamonds" or "Spades".
     */
    public Card() {
        double randomNum = Math.random() * 4.0;
        if (randomNum < 1.0)
            suit = "Hearts";
        else if (randomNum < 2.0)
            suit = "Clubs";
        else if (randomNum < 3.0)
            suit = "Diamonds";
        else
            suit = "Spades";
        randomNum = Math.random() * 13.0;
        number = (int) randomNum + 1;
    }
    /*
     * Creates a card with specified number and suit
     */
    public Card (int n, String s) {
        number = n;
        suit = s;
    }

    public int getNumber() {
        return number;
    }

    public String getSuit () {
        return suit;
    }


    public String cardString() {
        // System.out.println(number + " " + suit);
        String stringNum = "";
        switch (number) {
        case 1:
                stringNum = "Ace";
                break;
            case 2:
                stringNum = "Two";
                break;
            case 3:
                stringNum = "Three";
                break;
            case 4:
                stringNum = "Four";
                break;
            case 5:
                stringNum = "Five";
                break;
            case 6:
                stringNum = "Six";
                break;
            case 7:
                stringNum = "Seven";
                break;
            case 8:
                stringNum = "Eight";
                break;
            case 9:
                stringNum = "Nine";
                break;
            case 10:
                stringNum = "Ten";
                break;
            case 11:
                stringNum = "Jack";
                break;
            case 12:
                stringNum = "Queen";
                break;
            case 13:
                stringNum = "King";
                break;
            default:
                System.out.println("Error in Card - illegal number");
            }
            return stringNum + " of " + suit;
        }
    }


public class PackCards {

    private ArrayList<Card> pack;

    /*
     * Create a random pack of size n
     */
    public PackCards(int n) {
        Card c;
        pack = new ArrayList<Card>();
        for (int i = 1; i <= n; i++) {
            c = new Card();
            pack.add(c);
        }
    }

    public void printPack() {
        for (Card c : pack) {
            System.out.println(c.cardString());
        }
    }


    public Card findLargest() {

        if ( c.getNumber() > largest.getNumber() ) 
            largest = 
                else if (c.getNumber() == largest.getNumber() ) {
                    if (largest.getSuit().equals("Diamonds"))
                largest = largest.getNumber; 
                }
                else if (c.getNumber() == largest.getNumber() ) {
                    if (largest.getSuit().equals("Clubs"))
                        largest = largest.getNumber;
                }
                else if (c.getNumber() == largest.getNumber() ) {
                    if (largest.getSuit().equals("Hearts"))
                        largest = largest.getNumber;
                }

                else return;


    }

3 个答案:

答案 0 :(得分:1)

我会简化代码,以便更容易看到您要实现的目标。在Java 8中,您可以这样做。

import java.util.Random;

public class Card  {
    enum Suit {
        // must be in increasing order.
        Spades, Diamonds, Clubs, Hearts
    }

    static final Suit[] SUITS = Suit.values();

    private final int number;
    private final Suit suit;

    /*
     * Randomly creates a card numbered 1 to 13 (ace = 1!) and labelled "Hearts","Clubs","Diamonds" or "Spades".
     */
    public Card() {
        Random rand = new Random();
        suit = SUITS[rand.nextInt(SUITS.length)];
        number = rand.nextInt(13) + 1;
    }

    public int getNumber() {
        return number;
    }

    public Suit getSuit() {
        return suit;
    }

    static final String[] NAMES = ",Ace,Two,Three,Four,Five,Six,Seven,Eight,Nine,Ten,Jack,Queen,King".split(",");

    public String cardString() {
        assert number > 1 && number < NAMES.length;
        return NAMES[number] + " of " + suit;
    }
}

这也简化了您的包装

public class PackOfCards {
    private final List<Card> cards;

    public PackOfCards(int size) {
        // note duplicates are possible, i.e. ever card could be the same.
        cards = IntStream.range(0, size)
                .mapToObj(n -> new Card())
                .collect(Collectors.toList());
    }

    public Card findLargest() {
        return cards.stream().max(Comparator.comparing(Card::getNumber)
                .thenComparing(Card::getSuit)).get();
    }
}

答案 1 :(得分:1)

您可以更改 Card 类以实现 Comparable 界面。例如:

public class Card implements Comparable<Card> {
    ....// your current implementation for the Card class

    public int compareTo(Card another) {
        if (this.suit.compareTo(another.suit) == 0) {
            if (this.number < another.number) {
                return -1;
            } else if (this.number > another.number) {
                return 1;
            } else {
                return 0;
            }
        } else if (this.suit.compareTo("Diamonds") == 0) {
            // Diamonds being the lowest valued suit ...
            return -1;
        } else if (this.suit.compareTo("Clubs") == 0) {
            // ... then Clubs ...
            if (another.suit.compareTo("Diamonds") == 0) {
                return 1;
            } else {
                return -1;
            }
        } else if (this.suit.compareTo("Hearts") == 0) {
            // ... Hearts ...
            if (another.suit.compareTo("Spades") == 0) {
                return -1;
            } else {
                return 1;
            }
        } else {
            // ... and largest values, Spades
            return 1;
        }
    }
}

然后,您可以修改 PackCards 以将卡存储在有序集合中。例如:

pack = new TreeSet<Card>();

这样,包中的卡就是有序的,最后一张是最大的。

如果您希望将卡片添加到列表中,那么您可以通过这种方式获得最大的订单:

largest = Collections.max(pack);

答案 2 :(得分:0)

对于这类工作,您希望利用Java的面向对象特性,并对FaceValueSuit使用枚举。枚举按照您列出的顺序“自然排序”,使您的构造和字符串输出更容易:

public class Card implements Comparable<Card> {

  private FaceValue faceValue;
  private Suit suit;

  /*
   * Randomly creates a card numbered 1 to 13 (ace = 1!)
   * labelled "Hearts","Clubs","Diamonds" or "Spades".
   */
  public Card() {
    int randomSuit = (int)Math.floor(Math.random() * 4.0); //Number between 0 and 3, inclusive.
    int randomFace = (int)Math.floor(Math.random() * 13.0);
    this.faceValue = FaceValue.values()[randomFace];
    this.suit = Suit.values()[randomSuit];
  }

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

  // TODO Constructor that convert ints and strings to proper enums and call previous constructor

  public int compareTo(Card that) {
    int comparison = this.suit.compareTo(that.suit);
    return (comparison != 0) ? comparison : this.faceValue.compareTo(that.faceValue);
  }

  public String cardString() {
    return this.faceValue + " of " + this.suit;
  }

  public enum Suit{
    DIAMOND, CLUB, HEART, SPADE;
  }

  public enum FaceValue {
     ACE, ONE, TWO, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING;
  }  // You can modify this enum if you need to give back something more specific as the string value.
}

然后,对于Deck,您可以通过选择一个好的数据结构来简化事情,在这种情况下是TreeSet,它会自动使用您提供的compareTo函数用于对卡片进行分类的卡片:

public class Deck {
  //By using a Set we eliminate duplicates
  private final TreeSet<Card> cards;

  public Deck(int size) {
    cards = Sets.newTreeSet(IntStream.range(0, size)
                                     .mapToObj(n -> new Card())
                                     .collect(Collectors.toList());
  }

  //Because this is a TreeSet, finding the largest value is trivial.
  public Card findLargest() {
    return this.cards.last();
  }
}

如果您的套牌中的牌需要特殊字符串,则可以对FaceValue进行以下修改:

public enum FaceValue {
  ACE {
    public String toString() { return "Ace"; }
  }, 
  ONE {
    public String toString() { return "One"; }
  }, 
  ...  // Fill out the rest in the same manner.
  KING {
    public String toString() { return "King"; }
  }
}

请记住,在面向对象的编程中,最重要的规则是对象应该知道如何表现。因此,如果您发现自己编写了switch语句,则可能会将行为推迟到对象本身。在这种情况下,您需要创建分配给给定卡的子对象(FaceValueSuit枚举)。该卡会询问这些子部件的订购方式,以及他们应如何回应toString请求。