Newbie question: Arrays of classes?

Newbie question: Arrays of classes?

Post by Dave Rei » Sat, 15 Apr 2006 03:40:11


So I want to set up two classes...a FieldRecord class that has a whole
bunch of attributes, and then a PatientRecord class that looks like this:

// Definition of the PatientFieldRecord Class
class PatientRecord {
int patNumber ;
String patName;
String patHospID;
FieldRecord[] patField = new FieldRecord[50];
}

Is that legal? Can I have an array of a class inside another class
definition?

Because I'm trying to read in a text file and then stuffing what I find
into my PatientRecords. I set up an array of PatientRecords like this:

PatientRecord[] patientsInTreatment = new PatientRecord[50];

and then scan my text file, and when I find what I'm looking for I do this:

if(tokenSegment[0].equals("11")){
numberPatients++;
patientsInTreatment[(numberPatients - 1)].patNumber =
Integer.parseInt(tokenSegment[1]);

And it barfs at runtime at this last statement, giving me this error:
"Exception in thread "main" java.lang.NullPointerException".

I'm sure its something basic that I'm doing wrong, but I can't see what it
is. Thanks in advance...

dave
 
 
 

Newbie question: Arrays of classes?

Post by Patricia S » Sat, 15 Apr 2006 04:10:21


...

Declaring:

PatientRecord[] patientsInTreatment = new PatientRecord[50];

creates a reference variable, patientsInTreatment, suitable for pointing
to arrays of PatientRecord references. It initializes it with a pointer
to a newly created array containing 50 null references to PatientRecord.

If you want an element of the array to point to an instance of
PatientRecord, you need to do something like:

patientsInTreatment[(numberPatients - 1)] = new PatientRecord();

Patricia

 
 
 

Newbie question: Arrays of classes?

Post by Dave Rei » Sat, 15 Apr 2006 04:32:56

Patricia Shanahan < XXXX@XXXXX.COM > wrote in



That fixed it...and your explanation makes a lot of sense. Thanks!

dave
 
 
 

Newbie question: Arrays of classes?

Post by Roedy Gree » Sat, 15 Apr 2006 05:51:51

On Thu, 13 Apr 2006 18:40:11 +0000 (UTC), Dave Reid
< XXXX@XXXXX.COM > wrote, quoted or indirectly quoted someone who
said :

Yes. But more typically you would have an ArrayList instead of
FieldRecord[] since you likely want a variable number of FieldRecords.
--
Canadian Mind Products, Roedy Green.
http://www.yqcomputer.com/ Java custom programming, consulting and coaching.
 
 
 

Newbie question: Arrays of classes?

Post by Roedy Gree » Sat, 15 Apr 2006 05:55:10

On Thu, 13 Apr 2006 18:40:11 +0000 (UTC), Dave Reid
< XXXX@XXXXX.COM > wrote, quoted or indirectly quoted someone who
said :


What is null? put in some code to find out:

1. patientsInTreatment
2. patientsITreatmement[numberPatients -1]
3 tokensSegment[1];

I will hazard a guess it is 2. See
http://www.yqcomputer.com/ #ARRAY
--
Canadian Mind Products, Roedy Green.
http://www.yqcomputer.com/ Java custom programming, consulting and coaching.