2011-05-03 2 views
0

블랙 잭 카드 게임을 만들고 있습니다. 내 프로그램에있는 오류에 대해 혼란스러워합니다. 어떤 도움을 주시면 감사하겠습니다. 미리 감사드립니다! BlackJackCardGame.DealHands (BlackJackCardGame.java:197) BlackJackCardGame.PlayBlackJack (BlackJackCardGame에서 에서 스레드 "주요"java.lang.NullPointerException이 에서블랙 잭 카드 프로그램에서 NullPointerexception 오류와 혼동했습니다.

예외 :
이 내 코드를 실행하면 내가 오류입니다. 자바 : BlackJackCardGame.main (BlackJackCardGame.java:252 207) )

내 코드는 다음과 같습니다 :

import java.util.Scanner; 
//import java.util.*; 
public class BlackJackCardGame 
{ 
static class Player 
{ 
    private String Name; 
    private int handValue; 
    private boolean BlackJack; 
    private TheCard[] Hand; 
    public Player(String name) 
    { 
     this.Name = name; 
     this.handValue = 0; 
     this.BlackJack = false; 
     this.Hand = null; 
    } 
} 
private static Player[] InitializePlayers(int PlayerCount) 
{ 
    Player[] thePlayers = new Player[PlayerCount + 1]; 
    for(int i = 0; i < PlayerCount + 1; i++) 
    { 
     String tempName; 
     if (i == 0) 
     { 
      tempName = "Dealer"; 
     } 
     else 
     { 
      tempName = "Player_" + String.valueOf(i); 
     } 
     thePlayers[i] = new Player(tempName); 
    } 
    return thePlayers; 
} 

static class TheCard 
{ 
    // Java getter & setter 
    private String CardName; 
    private int CardRank; 
    private int Chosen; 

    public TheCard(int rank, String name) 
    { 
     this.CardName = name; 
     this.CardRank = rank; 
     this.Chosen = 0; 
    } 
} 

private static TheCard[] BuildDeck(int decks) 
{ 
    String[] Cards = {"2","3","4","5","6","7","8","9","10","Jack","Queen","King","Ace"}; 
    String[] Suits = {"Spades","Hearts","Diamonds","Clubs"}; 
    TheCard[] theDeck = new TheCard[Cards.length * Suits.length]; 
    //int String [] = {2,3,4,5,6,7,8,9,10,11,12,13,14}; 
    int[] Rank = {2,3,4,5,6,7,8,9,10,10,10,10,11}; 
    int cardnumber = 0; 
    for (int d = 0; d < decks; d++) 
    { 
     for (int i = 0; i < Cards.length; i++) 
     { 
      for (int j = 0; j < Suits.length; j++) 
      { 
       String deckcard = Cards[i]; 
       String suitcard = Suits[j]; 
       String cardname = deckcard + "-" + suitcard; 
       theDeck[cardnumber] = new TheCard(Rank[i], cardname); 
       cardnumber++; 
      } 
     } 
    } 
    return theDeck; 
} 

private static TheCard Deal(TheCard[] OrderedDeck) 
{ // this method uses Random method to "deal" a single card from the playing deck 
    TheCard thecard; 
    int NumberofCards = OrderedDeck.length; 
    int random = (int) (NumberofCards*Math.random()); 
    thecard = OrderedDeck[random]; 
    if (thecard.Chosen == 0)  // if available... 
    { 
     thecard.Chosen = 1;   // mark it taken... 
     return thecard; 
    } 
    else 
    { 
     return Deal(OrderedDeck); 
    } 
} 
private static int ShowCardOfDealer(Player player, int cardNumber) 
{ 
    System.out.println (player.Name + ", is holding a: "); 
    System.out.println (player.Hand[cardNumber].CardName); 
    int value = player.Hand[cardNumber].CardRank; 
    System.out.println ("..with value of: " + String.valueOf(value)); 
    return value; 
} 
private static void DealerPlays(TheCard[] deck,Player[] players) 
{ 
    Player currentPlayer = players[0];  // dealer first in array 
    int handValue = ShowHand(currentPlayer); 
    int choice = 1; 
     do 
     { 
      if (handValue < 17) 
      { 
       TheCard newCard = Deal(deck); 
       int numCards = currentPlayer.Hand.length; 
       currentPlayer.Hand[numCards + 1] = newCard; 
       handValue = ShowHand(currentPlayer); 
       if (handValue > 21) 
       { 
        System.out.println ("The Dealer has busted!"); 
        handValue = 0; // special signal that this value always loses 
        choice = 0;  
       } 
      } 
      else 
      { 
       System.out.println ("The Dealer stays."); 
       choice = 0; //dealer is forced to stay, =>17 
      } 

     } while (choice == 1); 
} 
private static void MakeChoices(TheCard[] deck,Player[] players) 
{ 
    for(int i = 1; i < players.length -1 ; i++) 
    { 
     Player currentPlayer = players[i]; 
     int handValue = ShowHand(currentPlayer); 
     Scanner input = new Scanner(System.in); 
     int choice = 0; 
     do 
     { 
      System.out.println ("Make your choice please. Type 1 for Hit or type 0 for Stay."); 
      choice = input.nextInt(); 
      if (choice == 1) 
      { 
       // DealAnotherCardToPlayerX 
       // what player is going to be updated 
       // add new card to players hand 
       TheCard newCard = Deal(deck); 
       int numCards = currentPlayer.Hand.length; 
       currentPlayer.Hand[numCards + 1] = newCard; 
       handValue = ShowHand(currentPlayer); 
       if (handValue > 21) 
       { 
        System.out.println ("You have busted!"); 
        handValue = 0; // special signal that this value always loses 
        choice = 0;  //this guy is done, loop to next player 
       } 
      } 
     } while (choice == 1); 
     currentPlayer.handValue = handValue; 
    } 
} 
private static void setBlackJackCase(Player player) 
{ 
    player.BlackJack = false; 
    if (player.Hand[0].CardRank == 10 && player.Hand[1].CardRank == 11) 
    { 
     player.BlackJack = true; 
    } 
    if (player.Hand[1].CardRank == 10 && player.Hand[0].CardRank == 11) 
    { 
     player.BlackJack = true; 
    } 
} 
private static int ShowHand(Player player) 
{ 
    int cards = player.Hand.length;  // get number of cards player x has 
    System.out.println (player.Name + ", you are holding: "); 
    int value = 0; 
    for (int c = 0; c < cards; c++) 
    { 
     System.out.println (player.Hand[c].CardName); 
     //value = value + player.Hand[c].CardRank; 
     value += player.Hand[c].CardRank; 
    } 
    setBlackJackCase(player); 
    System.out.println ("Your total card value is: " + String.valueOf(value)); 
    return value; 
} 
private static void DealHands(TheCard[] deck,Player[] players) 
{ 
    for (int c = 0; c < 2; c++) 
    { 
     for(int i = 1; i < players.length -1 ; i++) 
     { 
      TheCard card = Deal(deck); 
      players[i].Hand[c] = new TheCard(card.CardRank, card.CardName); 
     } 
     //give dealer card 
     TheCard card = Deal(deck); 
     players[0].Hand[c] = new TheCard(card.CardRank, card.CardName); 
    } 
} 
private static void PlayBlackJack(TheCard[] playingDeck, Player[] players) 
{ 

    DealHands(playingDeck, players); // everybody has their hands - ready for choices: 
    ShowCardOfDealer (players[0], 0); //shows dealer's turned up card 
    MakeChoices (playingDeck, players); // everybody is either out or at "stay" 
    DealerPlays (playingDeck, players); // Dealer "plays" and Dealer Rules 
    AnnounceWinners (players); 
} 
private static void AnnounceWinners(Player[] players) 
{ 
    int dealerHand = players[0].handValue; 
    for(int i = 1; i < players.length -1 ; i++) 
    { 
     int playerHand = players[i].handValue; 
     if (players[i].BlackJack) 
     { 
       System.out.println (players[i].Name + ", you have BlackJack! :) You WIN!"); 
     } 
     else 
     { 
      if (dealerHand == 0 && playerHand == 0) 
      { 
       System.out.println (players[i].Name + " has busted.."); 
      } 
      if (dealerHand >= playerHand) 
      { 
       System.out.println ("Dealer wins"); 
      } 
      else 
      { 
       System.out.println (players[i].Name + ", you WIN!"); 
      } 
     } 
    } 
} 
public static void main(String args[]) 
{ 

    System.out.println ("Welcome, to the game of Black Jack"); 
    Scanner input = new Scanner(System.in); 
    System.out.println ("How many decks of cards are in this game? Enter a number from 1 to 3."); 
    int decks = input.nextInt(); 
    System.out.println ("How many players are in this game? (Not counting the Dealer)"); 
    int numPlayers = input.nextInt(); 
    TheCard[] PlayingDeck = BuildDeck(decks); 
    Player[] thePlayers = InitializePlayers(numPlayers); 
    //loop 
     PlayBlackJack(PlayingDeck, thePlayers); 
     System.out.println ("Play Again? Type 'y' or 'n'"); 
    //test answer 
} 
} 
+0

당신은 당신의 DealHands 방법에 몇 가지 의견을 놓아야 그래서 우리는 당신이 따라서, (예외가 발생하는 위치 그건) –

+0

을 당신은 그것을 초기화 Player.Hand를 참조,하지만 결코하고 그 루프와 함께 할 시도하는 것을 알고 null 참조. 어딘가에 새로운 TheCard []에 지정해야합니다. – forsvarir

답변

1

참고 플레이어 생성자의 코드 줄 : this.Hand = null;.

2

문제를 쉽게 지적 할 수있는 충분한 정보를 제공하지는 않았지만 줄 번호를 볼 수 있으므로 필요한 모든 정보를 얻었습니다. 라인 197을 찾아서 그 라인의 모든 오브젝트를보십시오. 그 중 하나는 null이고 올바른 개체 인 것처럼 취급하려고합니다.

private static void DealHands(TheCard[] deck,Player[] players) 
{ 
    for (int c = 0; c < 2; c++) 
    { 
     for(int i = 1; i < players.length -1 ; i++) 
     { 
      TheCard card = Deal(deck); 
      players[i].Hand[c] = new TheCard(card.CardRank, card.CardName); 
     } 
     //give dealer card 
     TheCard card = Deal(deck); 
     players[0].Hand[c] = new TheCard(card.CardRank, card.CardName); 
    } 
} 

내 생각 엔 당신이 null 배열의 인덱스를 액세스하기 위해 플레이어의 Hand 당신의 Player 생성자, 그래서 players[i].Hand[c] 시도를 초기화하지 않은 것입니다. 먼저 배열을 길이에 맞게 초기화해야합니다.

1

당신은 당신의 플레이어 클래스 생성자에서 Player.Hand 배열을 올바르게

를 초기화하는 없습니다 (라인 16)는

this.Hand = null; 

를 설정하고 방법 라인 (19)에

private static Player[] InitializePlayers(int PlayerCount) 

, 당신은 다음을하려고 할 때, 당신은 이것을 갱신하지 않는다. (널 포인터) :

players[i].Hand[c] = new TheCard(card.CardRank, card.CardName); 

players [i] .Hand []가 null이므로 오류가 발생합니다. InitializePlayer 메서드에서 Hand를 null이 아닌 배열로 설정해야합니다.

(여담 정규 자바 협약 방법 및 반원 이름은 "initializePlayer"같아야 "InitializePlayer", "손"및 방법이어야 "손"와 같은 변수를 예 낮은 낙 경우처럼)

0

객체 경우

players[i].Hand[c] = new TheCard(card.CardRank, card.CardName); 

는 도트 연산자 .를 사용하여 개체에 액세스 할 때마다하는 NPE가 발생합니다 : 소스 코드 조각은 선 누락하지 않는 한 스택 추적을 참조 라인 197의 상단 라인 197은 이것이다 액세스되는 것은 null입니다. NPE는 참조가 null 인 배열 변수로 색인을 만들려고 할 때 throw 될 수도 있습니다. 그래서 용의자는 다음과 같습니다의

players 
players[i] 
players[i].Hand 
card 

하나는 위의 null해야합니다. 디버거를 사용하여 197 줄에서 깨고 각각의 용의자를 검사하는 것이 좋습니다.범인이 어느 것이 었는지 알게되면, 뒤로 물러서서 어떻게 처음에 null이되었는지 알아 내려고 시도 할 수 있습니다.

은 ( card.CardRankcard.CardName 위 포함되지 않습니다, 그들은 당신의 예외가 TheCard의 생성자 내에서 발생 된 것이 문제 인 것 때문입니다.)

1
public Player(String name) { 
     this.Name = name; 
     this.handValue = 0; 
     this.BlackJack = false; 
     this.Hand = null; 
} 

체크 라인 this.Hand을 = null; ; 플레이어 [0] .Hand [C] = 새로운 TheCard (card.CardRank, card.CardName) 여기 라인에

private static void DealHands(TheCard[] deck, Player[] players) { 
    for (int c = 0; c < 2; c++) { 
     for (int i = 1; i < players.length - 1; i++) { 
      TheCard card = Deal(deck); 
      players[i].Hand[c] = new TheCard(card.CardRank, card.CardName); 
     } 
     // give dealer card 
     TheCard card = Deal(deck); 
     System.out.print("Card == null" + card == null); 

     players[0].Hand[c] = new TheCard(card.CardRank, card.CardName); 
    } 

} 

: 다음은은 손을 사용

이렇게 선언하십시오. 손 = 새 TheCard [2]; // 여기에 2 단지 예

입니다 그리고, 당신은

private static void DealerPlays(TheCard[] deck, Player[] players) { 
    Player currentPlayer = players[0]; // dealer first in array 
    int handValue = ShowHand(currentPlayer); 
    int choice = 1; 
    do { 
     if (handValue < 17) { 
      TheCard newCard = Deal(deck); 
      int numCards = currentPlayer.Hand.length; 
      currentPlayer.Hand[numCards + 1] = newCard; 
      handValue = ShowHand(currentPlayer); 
      if (handValue > 21) { 
       System.out.println("The Dealer has busted!"); 
       handValue = 0; // special signal that this value always 
           // loses 
       choice = 0; 
      } 
     } else { 
      System.out.println("The Dealer stays."); 
      choice = 0; // dealer is forced to stay, =>17 
     } 

    } while (choice == 1); 
} 

확인 라인 아래 코드에서 또 다른 문제가 그것을 수정이 형 "는 ArrayIndexOutOfBoundsException"의 확실한 예외입니다.

int numCards = currentPlayer.Hand.length; 
currentPlayer.Hand[numCards + 1] = newCard; 
관련 문제