java - Adding objects to an array from an implemented class -
good morning, apologies if question complex/confusing. in intro java course , having difficulties 1 of assignments! guys on here seem have answer know can help!
this assignment create specifications shapes (rectangles , triangles), must implemeneted such:
all shapes must implement calculated interface calculates area/perimeter. shapemanger class stores calculated shapes in array capable of storing 10 objects...
public class app { public static void main(string[] args) { shapemanager sm = new shapemanager(); rectangle r1 = new rectangle(100,120,10,13); sm.addshape(r1); sm.dump(); } } public interface calculated { public double calculatearea(); public double calculateperimeter(); public void dump(); } public class rectangle implements calculated { private int xcoord, ycoord, length, width, rectanglearea, rectangleperimeter; public calculated rectangleshape; public rectangle(int xcoord, int ycoord, int length, int width) { xcoord = xcoord; ycoord = ycoord; length = length; width = width; } public double calculatearea() { rectanglearea = length * width; return rectanglearea; } public double calculateperimeter() { rectangleperimeter = (length *2) + (width * 2); return rectangleperimeter; } public void dump() { system.out.println("the area of rectangle = " + rectanglearea); system.out.println("the perimeter of rectangle =" + rectangleperimeter); } } public class shapemanager { private calculated[] calcarray; private calculated rectangle; public calculated shape; public shapemanager() { calcarray = new calculated[10]; } public void addshape(calculated s) { int address = 0; while (calcarray[address] != null) { address++; } calcarray[address] = s; } public void dump() { (int x = 0; x <= 9; x++) { if (calcarray[x] !=null) { calcarray[x].dump(); } } } }
currently output is:
the area of rectangle = 0 perimeter of rectangle =0
i stuck on doing wrong, , why output isnt calculated properly. assistance on appreciated, thank , patience!
allyso
change dump
method to:
public void dump() { system.out.println("the area of rectangle = " + calculatearea()); system.out.println("the perimeter of rectangle =" + calculateperimeter()); }
you can improve further removing 2 fields: rectanglearea
, rectangleperimeter
, make calculate functions this:
public double calculatearea() { return length * width; }
now save memory well. rename methods getarea
, getperimeter
.
Comments
Post a Comment