2015-06-12 90 views
-3

我不知道爲什麼需要初始化currentCard那裏(我在我的代碼中評論)。 這段代碼真的需要這個語句嗎?我不明白爲什麼初始化需要在這個代碼中的java

public class Card { 
    private String face; 
    private String suit; 

    public Card(String cardFace, String cardSuit) 
    { 
    face = cardFace; 
    suit = cardSuit; 
    } 

    public String toString() 
    { 
    return face + " of " + suit; 
    } 
} 

=========================================== ====================

import java.util.Random; 

public class DeckOfCards 
{ 
    private Card[] deck; 
    private int currentCard; 
    private static final int NUMBER_OF_CARDS = 52; 
    private static final Random randomNumbers = new Random(); 

    public DeckOfCards() 
    { 
    String[] faces = {"Ace", "Deuce", "Three", "Four", 
     "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", 
     "Queen", "King" }; 
    String[] suits = {"Hearts", "Diamonds", "Clubs", "Spades"}; 

    deck = new Card[NUMBER_OF_CARDS]; 
    currentCard = 0; 

    for(int count = 0; count < deck.length; count++) 
     deck[ count ] = 
     new Card(faces[ count % 13 ], suits[ count/13 ]); 
    } 
    public void shuffle() 
    { 
    currentCard = 0; // I do not know why initialization is needed 

    for(int first = 0; first < deck.length; first++) 
    { 
     int second = randomNumbers.nextInt(NUMBER_OF_CARDS); 

     Card temp = deck[ first ]; 
     deck[ first ] = deck[ second ]; 
     deck[ second ] = temp; 
    } 
    } 
    public Card dealCard() 
    { 
    if(currentCard < deck.length) 
     return deck[ currentCard++ ]; 
    else 
     return null; 
    } 
} 


public class DeckOfCardsTest 
{ 
    public static void main(String[] args) 
    { 
    DeckOfCards myDeckOfCards = new DeckOfCards(); 
    myDeckOfCards.shuffle(); 

    for(int i = 1; i <= 52; i++) 
    { 
     System.out.printf("%-19s", myDeckOfCards.dealCard()); 

     if(i % 4 ==0) 
     System.out.println(); 
    } 
    }  
} 
+1

什麼初始化? – nafas

+0

currentCard = 0;在洗牌方法 –

+0

@nafas我懷疑問題是關於'currentCard = 0; //我不知道爲什麼需要初始化。 – Pshemo

回答

1
  • currentCard說應對接下來的這卡(見dealCard()法)

  • shuffle()做了兩事情:1)它洗牌,2)重置currentCard,以便下一張要交易的卡是卡片0.

(該currentCard = 0沒有必要洗牌本身!)

相關問題