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();
    } 
}
2
  • Can you share the stack trace as well? Commented Dec 3, 2019 at 19:14
  • @flakes I'll try to edit it Commented Dec 3, 2019 at 20:36

1 Answer 1

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;
Sign up to request clarification or add additional context in comments.

3 Comments

Perfect explanation. Don't forget you can also use Arrays.fill(list, new CardTrick())
@KnowNoTrend Won't that just fill the entire array with exactly the same object (which is most probably not what you want in that case)?
@brimborium they don't randomize the cards. they'll be the same anyway.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.