Question

In a blackjack program I'm writing I'm getting a null pointer exception in a while loop I'm using.

Here is the loop itself:

int total = 0; 
  for (int x = 5; x <= hitOrStayCounter; x++) 
  {

    total = total + temp[x].getBJ(); //Line 57 where the error is occuring. 
  }

Here is where and hitOrStayCounter and temp are defined:

int hitOrStayCounter=5;
Card[] temp = new Card[300];

Here is the getBJ method:

public int getBJ()
{
return bJValue; 
}

I suspect it is because I'm trying to use an array inside of my loop but inserting an int value into the brackets. I've tried to solve it and was wondering if you guys could help give me a solution. I couldn't find any similar questions, but if you find one please direct me to it and I'll delete this. Thanks for your time.

java.lang.NullPointerException
at Blackjack.main(Blackjack.java:57)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at       edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:272)

And then here is the loop where I initialized my temp values.

 while (hitOrStay.equalsIgnoreCase("hit"))
  {
    temp[hitOrStayCounter] = cardDeck.deal();
    System.out.println("You are delt a " + temp[hitOrStayCounter].getBJ()); 
    hitOrStayCounter = hitOrStayCounter + 2;
    System.out.println("Would you like to hit again?"); 
    hitOrStay = keyboard.next(); 
  }
Was it helpful?

Solution

Your hitOrStayCounter is 5. And you are starting your loop from 5.

for (int x = 0; x <= hitOrStayCounter; x++) 
{
    total = total + temp[x].getBJ(); 
}

If you are incriminating hitOrStayCounter, then it's ok.

Make sure your temp object is inialized.

Card[] temp = new Card[300]; This will not initialize

This will create 300 variables. Like

Card c1;
Card c2;..

You have to allocate each object as temp[0]= new Card(); Do it in a loop. I am just giving example

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top