Java question

This topic is 4526 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

Recommended Posts

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

Share on other sites
You have to create the particles, before using them:

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

Share on other sites

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

Share on other sites
Quote:
 Original post by Anonymous Posterint 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

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

Particle[] pSmall = new Particle[numParticles];

Share on other sites
Quote:
 Original post by templateI 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.

Share on other sites
Quote:
 Original post by cyberninjaruIt 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.

• 18
• 11
• 16
• 9
• 51
• Forum Statistics

• Total Topics
631396
• Total Posts
2999784
×