我在java中用于纸牌游戏的直接方法存在问题

时间:2016-11-18 07:18:56

标签: java arrays object methods

我的计算机科学课程有一个涉及制作纸牌游戏的项目。这是对卡片的基本看法。

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。直线是卡的值连续而没有循环的条件。

1 个答案:

答案 0 :(得分:0)

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