纸牌游戏 - 战争JAVA

时间:2015-11-05 02:08:36

标签: java nullpointerexception

这是我的错误消息:

 Round 0 of The War 
Player 0: Exception in thread "main" java.lang.NullPointerException
    at WAR1.printHand(WAR1.java:113)
    at WAR1.main(WAR1.java:93)

这是代码:

import java.util.Scanner;


public class WAR1 {

    private int cardNum;
    final static String[] suits = {"Spades", "Hearts", "Diamonds", "Clubs"};
    final static String[] ranks = {"2", "3","4","5","6","7","8", "9","10", "Jack", "Queen", "King", "Ace"};

    WAR1 (int theCardNum) {
        setCardNum (theCardNum);
    }

    public void setCardNum (int theCard) {
        cardNum = (theCard >= 0 && theCard <= 51)? theCard: 0;
    }

    public int getCardNum() {
        return cardNum;
    }

    public String toString() {
        return ranks[cardNum%13] + " of " + suits[cardNum/13];
    }

    public String getSuit() {
        return suits[cardNum/13];
    }

    public String getRank() {
        return ranks[cardNum%13];
    }

    public int getValue() {
        return cardNum%13;
    } 



    private WAR1[] deck = new WAR1[52];
    private int topCard;

    WAR1() {

        topCard = 0;

        for (int i = 0; i < deck.length; i++)
            deck[i] = new WAR1();

    }

    public void shuffle() {

        topCard = 0;

        for (int i = 0; i < 1000; i++) {
            int j = (int)(Math.random()*52);
            int k = (int)(Math.random()*52);
            WAR1 tmpCard = deck[j];
            deck[j] = deck[k];
            deck[k] = tmpCard;
        } 
   }

    public WAR1 dealCard() {
        WAR1 theCard;
        if (topCard < deck.length) {
            theCard = deck[topCard];
            topCard++;
        }
        else
            theCard = null;

        return theCard;
    }



    public static void main(String[] args) {

        WAR1[][] hands = new WAR1[2][1];
         Deck myDeck = new Deck();

        for (int i = 0; i < 26; i++) {
            System.out.printf("\n Round %s of The War \n", i);


                for (int player = 0; player < hands.length; player++)
                    hands[player][0] = myDeck.dealCard();

            for (int player = 0; player < hands.length; player++) {
                System.out.printf("Player %d: ", player);
                printHand(hands[player]);
            }

            int player1 = hands[0][0].getValue(); 
            int player2 = hands[1][0].getValue();

            if (player1 > player2)
                System.out.println("Player One Wins The War");
            else if (player2 > player1)
                System.out.println("Player Two Wins The War");
            else
                System.out.println("The War Is A Tie");

        }
    }


    public static void printHand(WAR1[] hand) {

        for (int card = 0; card < hand.length; card++)
            System.out.printf("%s", hand[card].toString());

        System.out.println();

    } 
}

我做错了什么?

0 个答案:

没有答案