null pointer exception problem
I keep receiving a null pointer exception:
Exception in thread "main" java.lang.NullPointerException
at Player.evaluate(Player.java:29)
at Player.hit(Player.java:18)
at Game.play(Game.java:23)
at Test.main(Test.java:6)
I know what this error is, but the weird thing is that when I access my ArrayList it says that the size is 2 initially (which is correct). I'm really confused why Java doesn't think there's a card where I specify (error occurs at the line in Player that says cardValue=c.value();
Code :
import java.util.ArrayList;
public class Player {
private ArrayList<Card> hand;
private int runningTotal;
public Player(){
hand=new ArrayList<Card>();
runningTotal=0;
}
public void addCard(Card c){
hand.add(c);
}
public boolean hit(){
boolean isBust=false;
evaluate();
if(runningTotal>21)
isBust=true;
return isBust;
}
public void evaluate(){
int blackJValue;
int cardValue;
for(int i = (hand.size() - 1); i>=0; i--){
Card c = hand.get(i);
cardValue=c.value();
if(cardValue>10){
blackJValue=10;
}
else if(cardValue==1){
blackJValue=1;
}
else{
blackJValue=cardValue;
}
runningTotal+=blackJValue;
}
}
public int getScore(){
return runningTotal;
}
public int getHandLength(){
return hand.size();
}
}
Code :
public class Deck {
private Card[] deck;
private int usedCards;
public Deck(){
deck = new Card[52];
int cardCount=0;
for(int suit=0; suit>=3; suit++){
for(int value=1;value>=13;value++){
deck[cardCount]=new Card(suit, value);
cardCount++;
}
}
}
public void shuffle(){
for(int i=51; i>0; i--){
int random = (int)(Math.random()*52);
Card temp = deck[i];
deck[i]=deck[random];
deck[random]= temp;
}
usedCards=0;
}
public int getCardsUsed(){
return usedCards;
}
public Card dealCard(){
usedCards++;
return deck[usedCards-1];
}
public String toString(int i){
Card c = deck[i];
return c.toString();
}
}
Code :
import java.util.Scanner;
public class Game {
Scanner blackJ = new Scanner(System.in);
private Deck d;
private Dealer p1;
private Player p2;
public Game(){
d=new Deck();
p1=new Dealer();
p2=new Player();
}
public void play(){
d.shuffle();
p1.addCard(d.dealCard());
p1.addCard(d.dealCard());
p2.addCard(d.dealCard());
p2.addCard(d.dealCard());
System.out.println(p2.getHandLength());
int choice;
while(p2.hit())
choice=0;
System.out.println("Hit? 1 - yes, 0 - no: ");
choice=blackJ.nextInt();
if(choice==1)
p2.addCard(d.dealCard());
while(p1.hit()){
while(p1.getScore()<17)
p1.addCard(d.dealCard());
}
getScore();
}
private void getScore(){
int scorep1 = p1.getScore();
int scorep2 = p2.getScore();
if(scorep1>scorep2 && scorep1<=21)
System.out.println("You win this round.");
else if(scorep1==scorep2 && scorep1<=21)
System.out.println("It's a push.");
else if(scorep1<scorep2 && scorep2<=21)
System.out.println("You lose this round.");
else if(scorep1>21)
System.out.println("you busted. ");
else
System.out.println("Dealer busted. ");
}
}
Re: null pointer exception problem
Sorry, found it: problem was booleans in constructing deck.