We closed this forum 18 June 2010. It has served us well since 2005 as the ALPHA forum did before it from 2002 to 2005. New discussions are ongoing at the new URL http://forum.processing.org. You'll need to sign up and get a new user account. We're sorry about that inconvenience, but we think it's better in the long run. The content on this forum will remain online.
IndexProgramming Questions & HelpSyntax Questions › define class problem
Page Index Toggle Pages: 1
define class problem (Read 683 times)
define class problem
Sep 11th, 2008, 5:29pm
 
Hi,
I'm very new to object programming. usually I just doing procedural scripting for my course work.

As I cannot find the equvialent function of Type in Processing. therefore, I try to construct a class to represent a point with x, y, z and a value of v.

part of my script as follow;

Point3D vertices [];
Point3D vpts [][][];

void setup () {
 size(550, 550, P3D);
 vpts = new Point3D [2][2][2];
 for (int i=0; i<2; i++) {
   for (int j=0; j<2; j++) {
     for (int k=0; k<2; k++) {
       vpts[i][j][k].x = 1;
       vpts[i][j][k].y = 2;
       vpts[i][j][k].z = 3;
       vpts[i][j][k].v = 4;
     }
   }
 }
 println(vpts);
 
 vertices = new Point3D [2];
 for (int i=0; i<2; i++) {
   vertices[i].x = 20;
   vertices[i].y = 20;
   vertices[i].z = 20;
   vertices[i].v = 20;
 }
 println(vertices);
}



class Point3D {
 float x, y, z, v;
 
 // constructors
 Point3D(){
 }

 Point3D(float x, float y, float z, float v){
   this.x = x;
   this.y = y;
   this.z = z;
   this.v = v;    //store value
 }
}

error message as follow;
Exception in thread "Animation Thread" java.lang.NullPointerException

at classError.setup(classError.java:10)

at processing.core.PApplet.handleDraw(PApplet.java:1377)

at processing.core.PApplet.run(PApplet.java:1305)

at java.lang.Thread.run(Thread.java:595)

would any one can give some advice? I'm not sure, seems the synatx of class have problem.

many thanks
Re: define class problem
Reply #1 - Sep 12th, 2008, 2:52pm
 
You do a classical mistake in Java: the vpts = new Point3D [2][2][2];  line creates the array itself (in C that would be an array of pointers to objects yet to be created), not the objects. Ie. you declare references to objects of given type, but at this point, all these references are null.
You have to create each object in the loop:

Code:
void setup () {
 size(550, 550, P3D);
 vpts = new Point3D [2][2][2];
 for (int i=0; i<2; i++) {
   for (int j=0; j<2; j++) {
for (int k=0; k<2; k++) {
  vpts[i][j][k] = new Point3D(1, 2, 3, 4);
}
   }
 }
 println(vpts);
 
 vertices = new Point3D [2];
 for (int i=0; i<2; i++) {
   vertices[i] = new Point3D(20, 20, 20, 20);
 }
 println(vertices);
}

Plus it uses the constructor, giving a nicer look to the code! Wink
Re: define class problem
Reply #2 - Sep 12th, 2008, 5:41pm
 
thank you very much. I should study more about Java.
Page Index Toggle Pages: 1