Using get and set methods with arrays in java -
part of java assignment have requires me use set method input details array. far have following method set details
public void setcanopy(string uniqueref, string modelname, int width, int height, int depth, int crewtobuild, double timetobuild, double trailerlength, string available) { this.uniqueref = uniqueref; this.modelname = modelname; this.width = width; this.height = height; this.depth = depth; this.timetobuild = timetobuild; this.available = available; this.crewtobuild = crewtobuild; this.trailerlength = trailerlength; }
this method works fine long it's used input details constructor, when try use array nullpointerexception.
i have display these details later on using methods. i'm using following method display these again, works if i'm using constructors.
public static void displaycanopydetails(canopy c) { system.out.println("canopy reference number: " + c.getuniqueref() + "\ncanopy model name: " + c.getmodelname() + "\ncanopy dimensions (cm) - width: " + c.getwidth() + " height: " + c.getheight() + " depth: " + c.getdepth() + "\ncrew build: " + c.getcrewtobuild() + "\ntime build canopy (minutes): " + c.gettimetobuild() + "\ntrailer length: " + c.gettrailerlength() + "\navailability: " + c.getavailable()); }
any getting these working arrays appreciated. thanks.
in main method have
tentdetails(c[0]);
which calls method
public static void tentdetails(canopy c1,) { c1.setcanopy("can123", "model1", 500, 200, 500, 5, 15, 10, "available"); }
the nullpointerexception error happens when tries run method.
when declare array creates empty "bag" objects doesn't create objects themselves. when use method on object in array nullpointerexception because object null. cannot execute methods on object before creating first. example:
canopy[] canopy=new canopy[5]; //creates 'storage' 5 canopy objects system.out.println(canopy[0]); //prints null , throws npe if execute method canopy[0]=new canopy(); //create new canopy object , insert in array system.out.println(canopy[0]); //not null anymore - can execute methods canopy[0].setcanopy("can123", "model1", 500, 200, 500, 5, 15, 10, "available"); // works fine
Comments
Post a Comment