Java question

Started by
5 comments, last by haegarr 18 years, 2 months ago
I'm writing an animation program for my Java class. It consists of two balls bouncing around the screen. Whenever the balls collide, I want to have particles explode in a random direction at the point of intersection. Here is my question. Is it possible to make an array of class objects in Java? I tried this and it compiled correctly, but when I ran my applet, it threw a lot of NullPointerExceptions at me. Here is how I initialize the array: int numParticles = 100; Particle pSmall[] = new Particle[numParticles]; It threw an exception at every place I tried to set a value to the selected particle. Anyone have any ideas how to fix this? Thanks in advance. Cyber
Advertisement
You have to create the particles, before using them:

int numParticles = 100;
Particle pSmall[] = new Particle[numParticles];
for (int i = 0; i <


int numParticles = 100;
Particle pSmall[] = new Particle[numParticles];
for (int i = 0; i
Quote:Original post by Anonymous Poster


int numParticles = 100;
Particle pSmall[] = new Particle[numParticles];
for (int i = 0; i


int numParticles = 100;Particle pSmall[] = new Particle[numParticles];for (int i = 0; i < 100; ++i) {   pSmall = new Particle();}


maybe
I thought in Java you had to have the square brackets after the type (unlike C/C++) i.e.

Particle[] pSmall = new Particle[numParticles];

Quote:Original post by template
I thought in Java you had to have the square brackets after the type (unlike C/C++) i.e.

Particle[] pSmall = new Particle[numParticles];


Both notations are correct in java.
Quote:Original post by cyberninjaru
It threw an exception at every place I tried to set a value to the selected particle.

Does this mean that the access _of_ the array's references to a Particle fails, or that the access to a Particle _by_ the array's references fails?

I assume the former one. You has to have in mind that all and every object in Java has to be allocated by a new operation. There is no possibility of embedded object like in C++. So, after allocating the array, you haven't an array of objects but an array of references to objects. Those references could be null like any other object reference in Java. So you have to set the references explicitely to refer to an object before accessing the object, e.g. like the AP and Boder have shown.

This topic is closed to new replies.

Advertisement