【问题标题】:I'm having an issue with my straight method in java for a card game我在 Java 中用于纸牌游戏的直接方法有问题
【发布时间】:2016-11-18 07:18:56
【问题描述】:

我的计算机科学课程有一个项目,其中涉及制作纸牌游戏。这是卡片的基本介绍。

public Card(int value, int suit) {
if (value < 1 || value > 9) {
    throw new RuntimeException("Illegal card value attempted.  The " +
            "acceptible range is 1 to 9.  You tried " + value);
}
if (suit < 0 || suit > 4) {
    throw new RuntimeException("Illegal suit attempted.  The  " + 
            "acceptible range is 0 to 4.  You tried " + suit);
}
this.suit = suit;
this.value = value;
}
public int getValue() {
return value;
}

我的问题是我的直接方法似乎不起作用。我试图做的是从最小到最大组织我手中的卡片,然后做一些 if 语句。

public static boolean hasStraight(Card [] cards) {
    boolean exist = false;
    Card[] other = new Card[cards.length];
    for (int i = 0; i<cards.length; i++){
        for (int j = 0; j<cards.length; j++){
            if (cards[i].getValue()>cards[j].getValue()){
                other[i]=cards[j];
                other[j]=cards[i];
            }
        }
    }
    if (other[0].getValue()==1 && other[1].getValue()==2 && other[2].getValue()==3 && other[3].getValue()==4 && other[4].getValue()==5){
        exist = true;
    }
    else if (other[0].getValue()==2 && other[1].getValue()==3 && other[2].getValue()==4 && other[3].getValue()==5 && other[4].getValue()==6){
        exist = true;
    }
    else if (other[0].getValue()==3 && other[1].getValue()==4 && other[2].getValue()==5 && other[3].getValue()==6 && other[4].getValue()==7){
        exist = true;
    }
    else if (other[0].getValue()==4 && other[1].getValue()==5 && other[2].getValue()==6 && other[3].getValue()==7 && other[4].getValue()==8){
        exist = true;
    }
    else if (other[0].getValue()==5 && other[1].getValue()==6 && other[2].getValue()==7 && other[3].getValue()==8 && other[4].getValue()==9){
        exist = true;
    }
    else if (other[0].getValue()==6 && other[1].getValue()==7 && other[2].getValue()==8 && other[3].getValue()==9 && other[4].getValue()==1){
        exist = true;
    }
    return exist;
}

Card[] 的长度始终为 5。每次调用该方法时,即使没有顺子,它也会返回 true。顺子是牌的值是连续的而不循环的情况。

【问题讨论】:

  • 我不确定您要在 other[i]=cards[j] other[j]=cards[i]; 中做什么,但这不是交换。您需要一个临时变量来进行交换。也许你应该使用Arrays.sort
  • 九张牌值和五种花色?这是一个奇怪的甲板。更重要的是,您是否在调试器中单步执行了代码?与在此处发布相比,这将使您能够更快、更轻松地找到逻辑中的错误。
  • 为什么不对cards-deck 进行排序? “其他”数组的意图是什么?您是否不允许重新订购初始套牌(因为您必须保留订单以使用其他可能的方法)?如果是这样:将卡片组复制到其他卡片组并对其进行排序。如果不是:只需对卡片组进行排序并删除other-array
  • 他必须根据价值排序而不是西装,但这只需要自定义比较器实现。
  • 不要编写和调试您自己的排序例程,而是查看Arrays.sort。此外,正如其他人所指出的,您有一副 45 张牌,有 5 张花色。我认为这是故意的。

标签: java arrays object methods


【解决方案1】:

在我看来,循环中的排序不起作用。您可以改用Arrays.sort,但您必须为其编写Comparator 或使Card 实现Comparable。循环后的代码可以简化为检查最后一张和第一张卡的差是否为4。

【讨论】:

  • 不能使用Collections.sort,除非项目在一个集合中;它们目前在一个普通数组中,但 Arrays.sort 可以工作。
猜你喜欢
  • 1970-01-01
  • 2023-03-28
  • 2013-11-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-29
相关资源
最近更新 更多