Trouble Creating An Array Of Objects in Java -
this sticking point: need create array of chair objects default woodtype. able declare array itself, values null. when try instantiate each chair object in array, errors. i'm not sure doing wrong when trying instantiate, please help.
public class passign3 { public static void main(string[] args) { tableset set1 = new tableset(); tableset set2 = new tableset(5, 7, 4); // chair chr1 = new chair();//this works properly, setting wood oak // chair chr2 = new chair("pine");//works } } class tableset { table table = new table(); private int numofchairs = 2; //creates array can hold "numofchairs" references same num of //chair objects; not instantiate chair objects!!! chair[] chairarr = new chair[numofchairs]; //instantiate each chair object length of array //this loop not work; error: illegal start of type (int = 0; < numofchairs.length; i++) { chairarr[i] = new chair(); } public tableset() { } public tableset(double width, double length, int numofchairs) { table = new table(width, length); this.numofchairs = numofchairs; chairarr = new chair[numofchairs]; //this loop not work; error: int cannot dereferenced (int = 0; < numofchairs.length; i++) { chairarr[i] = new chair(); } } public void setnumofchairs(int numofchairs) { this.numofchairs = numofchairs; } public int getnumofchairs() { return numofchairs; } public string getchairwoodtype() { return chairarr[0].getwoodtype(); } } class table { private double width = 6; private double length = 4; public table() { } public table(double width, double length) { this.width = width; this.length = length; } public void setwidth(double width) { this.width = (width < 0) ? 0 : width; } public void setlength(double length) { this.length = (length < 0) ? 0 : width; } public double getwidth() { return width; } public double getlength() { return length; } } class chair { private string woodtype = "oak"; public chair() { } public chair(string woodtype) { this.woodtype = woodtype; } public void setwoodtype(string woodtype) { this.woodtype = woodtype; } public string getwoodtype() { return woodtype; } }
int
simple type in java , not have methods or fields. omit .length
, error gone. seems me stores actual number of chairs (2).
Comments
Post a Comment