输出的差异 - Java

时间:2016-06-30 11:24:13

标签: java

我的代码中没有出现错误消息。 但是,当我在main中输入代码并调用我的方法时,我得到不同的输出。

package card;

import java.util.Arrays;
import java.util.Random;

/**
 *

 */
public class Card {

    /**
     * @param args the command line arguments
     */
    static String rank;
    static String suit;
    static String[] ranks = {"2","3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"};
    static String[] suits = {"Spades","Hearts", "Clubs", "Diamonds"};
    static Card[] deck = new Card[52];

   public Card(String rank, String suit)
   {
      this.rank = rank;
      this.suit = suit;
   }

   public static String getRank()
   {
       return rank;
   }

   public static void setRank(String r)
   {
       rank = r;
   }

    public static String getSuit()
   {
       return suit;
   }

   public static void setSuit(String s)
   {
       suit = s;
   }





    public static void init(Card[] deck)
    {
        for(int x = 0; x<deck.length; x++)
        {
            Card newCard = new Card(ranks[x%13], suits[x/13]);
            deck[x] = newCard;
        }
    }

    public static void swap(Card[] deck, int a, int b)
    {
        Card temp = deck[a];
        deck[a] = deck[b];
        deck[b] = temp;
    }

    public static void shuffle(Card[] deck)
    {
        Random rnd = new Random();
        for(int x = 0; x<deck.length; x++)
        {
            swap(deck, x, (rnd.nextInt(deck.length)));
        }
    }

    public static void print(Card[] deck)
    {   
        for(int x =0; x<deck.length; x++)
        {
              System.out.println(deck[x].getRank() + " of " + deck[x].getSuit());
        }

    }


    public static void main(String[] args) {
        // TODO code application logic here


    for(int x = 0; x<deck.length; x++)
    {
        Card cards = new Card(ranks[x%13], suits[x/13]);
        deck[x] = cards;
        System.out.println(deck[x].getRank() + " of " + deck[x].getSuit());

        //init(deck);
        //print(deck);
    }


  }

}

为了在没有任何方法的情况下手动执行主代码,我将获得正确的输出:

例如

10 of Diamonds
J of Diamonds
Q of Diamonds
K of Diamonds

但是当我调用这些方法时,我得到以下输出:

A of Diamonds
A of Diamonds
A of Diamonds
A of Diamonds
A of Diamonds

怎么了?

1 个答案:

答案 0 :(得分:2)

以下静态成员

static String rank;
static String suit;

不应该是静态的,因为每张卡应该有不同的值:

String rank;
String suit;