0

Basically I'm trying to create an array of objects, that has two arrays inside of it, however when I try and populate these I keep getting a null pointer, but when I populate the object without making an array of objects it seems to work.

And I keep getting --> Exception in thread "main" java.lang.NullPointerException

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;

public class CardTrick{
    int[] combo;
    int[] cardTeller;

    public CardTrick() 
    {
        combo = new int[3];
        for (int j = 0; j < 3; j++) {
            combo[j] = 0;
        }
        cardTeller = new int[2];  
        for (int j = 0; j < 2; j++) {
            cardTeller[j] = 0;
        }   
    }

    public CardTrick(CardTrick c) { // notice the parameter is an object

        combo = new int[3];
        for (int j = 0; j < 3; j++) {
            combo[j] = 0;
        }
        cardTeller = new int[2];  
        for (int j = 0; j < 2; j++) {
            cardTeller[j] = 0;
        }   

    }
    public void whatCards(){
        int num = 0;
        CardTrick[] list = new CardTrick[56];

        list[0].combo[1] = 1;
        list[0].combo[2] = 1;
        list[0].cardTeller[0] = 1;
        list[0].cardTeller[1] = 1;

        System.out.println(list[0].combo[1]);

    }

    public static void main(String[] args){
        CardTrick ct = new CardTrick();
        ct.whatCards();
    } 
}
FailingCoder
  • 757
  • 1
  • 8
  • 20
Lauren
  • 11
  • 4

1 Answers1

3

The problem is in these lines of code

CardTrick[] list = new CardTrick[56];

list[0].combo[1] = 1;

You created an array of objects, but your objects themselves aren't instantiated thus the NullPointerException is thrown.

You have to instantiate each cell of the array before accessing it

CardTrick[] list = new CardTrick[56];
list[0] = new CardTrick();

list[0].combo[1] = 1;
Michał Krzywański
  • 15,659
  • 4
  • 36
  • 63
b.GHILAS
  • 2,273
  • 1
  • 8
  • 16