程序运行不正常

时间:2015-11-21 22:58:04

标签: java

我正在尝试编写一个应该构建52张卡片的代码,然后将卡片交给n个玩家(某些玩家可能有额外的卡片)。获胜者是带有黑桃卡牌的人。

public class CardGame {
  public static void main(String[] args) { 

    int numberOfPlayers = Integer.parseInt(args[0]);
    CardPile deck = CardPile.makeFullDeck(); 
    CardPile [] players = new CardPile[numberOfPlayers];

    for (int i=0;i<numberOfPlayers;i++) {  
      int numofnum = i%numberOfPlayers;

      players[i] = new CardPile();
    }

    for (int i=0;i<52;i++) { 
      int numofnum =i%numberOfPlayers;

      CardPile curPlayer = players[i%numberOfPlayers];
      Card nextCard = deck.get(i);
      players[numofnum].addToBottom(nextCard); 

    }

    for (int i=0;i<numberOfPlayers;i++) {  

      if (players[i].find(Suit.SPADES, Value.ACE) != -1) {

        System.out.println("Player " + i + " is the winner");
      }
    }

  }
}

这是CardPile

public class CardPile{
  private Card[] cards; 
  private int numCards;


  public static void main(String[] args){


  }


  public CardPile(){
    Card[] constructor = new Card[52]; 
    cards = constructor; 
    numCards = 0;  
  }

  public boolean isEmpty(){
    return this.numCards==0; 
  }

  public void addToBottom(Card c){
    int i = 0;
    for(i = 0;i<52;i++){  
      if(cards[i]==null){
        break;
      }
    }
    numCards = i; 
    cards[i] = c; 
  }


  public Card get(int i){
    return cards[i]; 
  }

  public Card remove(int i){
    Card removed = cards[i];
    for(i = i;i<51;i++){
      cards[i]=cards[i+1];  
    }
    cards[51]= null; 
    numCards=numCards-1;
    return removed;
  }

  public int find(Suit a,Value b){
    int i = 0;
    for(i=0;i<52;i++){
      if(cards[i].getSuit()==a && cards[i].getValue()==b){  
        break;
      }
      else{
        i = -1; 
        return i;
      }
    }
    return i;
  }

  public  String toString(){
    String x = "";  
    String y = "";

    for(int i=0;i<numCards;i++){  
      y = cards[i].toString();
      x = x + i + "." + y +" "; 
    }
    return x;

  }

  public static CardPile makeFullDeck(){

    CardPile pile = new CardPile();  
    for(Value v: Value.values()){
      for(Suit s: Suit.values()){
        pile.addToBottom(new Card(s,v)); 
      }
    }

    UtilityCode.shuffle(pile.cards, pile.numCards);  

    return pile;

  }


}

我的问题是,有时当我运行CardGame时,它打印出“玩家x是胜利者”,但有时它不打印任何东西。有人可以帮我吗?谢谢

1 个答案:

答案 0 :(得分:1)

CardPile.find()将返回-1,除非第一张卡片是被搜索的卡片。将其更改为:

public int find(Suit a,Value b){
    for(int i=0;i<52;i++){
      if(cards[i].getSuit()==a && cards[i].getValue()==b){  
        return i;
      }
    }
    return -1;
  }