1

I am new to java

This is my first real project (card game: Blackjack)

I made a test class and was told to use print-lines to try and pinpoint my problem, however I cannot comprehend why the null exception keeps showing up. I don't have anything set to null, and my array has been initialized using the "new". I can also post the IO class, however i'm fairly certain that the issue is not within that.

  public static void main(String[] args) {
    // Initializing just a single player
    Player x = new Player();
    // Quick test to make sure it reads the initial value of 0
    System.out.println(x.getMoney());

    // Testing user input using an IO class given
    System.out.println("How much would you guys like to play with?(Bet money)");
    double y = IO.readDouble();
    x.addMoney(y);
    System.out.println(x.getMoney());
    // Successfully prints out the value y

    Player[] total = new Player[4];
    total[1].addMoney(y);

    System.out.println(total[1].getMoney());
    // returns the null pointer exception error

  }

Here is my Player class

package Blackjack;

public class Player {

  private Hand hand = new Hand();
  private double currentMoney = 0;

  private double bet = 0;

  public void takeCard(Card h) {
    hand.addCardToHand(h);
  }

  public double getBet() {
    return bet;
  }

  public double getMoney() {
    return currentMoney;
  }

  public void betMoney(double k) {
    currentMoney = -k;
    bet = +k;
  }

  public void addMoney(double k) {
    currentMoney = currentMoney + k;
  }

  public void resetBet() {
    bet = 0;
  }

I can see maybe the problem being within my initialization of hand, however I the fact that I don't ask to return anything from the hand portion of the code leads me to believe that's not where the issue lies.

JFPicard
  • 5,029
  • 3
  • 19
  • 43
hamdoe
  • 111
  • 1
  • 1
  • 6

1 Answers1

5
Player[] total = new Player[4];
total[1].addMoney(y);

when you initialize an object array, it is "filled" with null references. So in this case, total[1] will return null, unless you assign a Player instance to index 1: total[1] = new Player();

andrucz
  • 1,971
  • 2
  • 18
  • 30