Right now I am doing the classic shape program involving shape classes. I can do the create circle or rectangle object without any problem. But when I get perimeter or area of all the objects, it turns out all the objects are null. Here is the code:
//Case menu selection actions
Here it the instance variables and arrays
private int menu_select;
private int i=0;
private Shape[] s = new Shape[10];
Here is the menu options
public static void display_menu()
{
System.out.print("Choose an option:\n"+
"1-Add a new circle\n"+
"2-Add a new rectangle\n"+
"3-Delete all shapes\n"+
"4-Scale all shapes\n"+
"5-Display perimeter of all shapes\n"+
"6-Display the area of all shapes\n"+
"7-Enter scale factor\n"+
"8-Exit program\n");
}
Here is the the menu code
Here is the switch
//Case menu selection actions
public void select_case()
{
if(i<=10)
{
switch (menu_select)
{
case 1: Circle c = new Circle(1);
s[i]=c;
i++;
break;
case 2: Rectangle r = new Rectangle(1,1);
s[i]=r;
i++;
break;
case 3: s=null;
i=0;
break;
case 4: Scanner input = new Scanner(System.in);
double d = input.nextDouble();
for(int i=0; i<s.length; i++)
{
s[i].setScaleFactor(d);
}
break;
case 5: for(int i=0; i<s.length; i++)
{
if(s[i] != null)
{
System.out.println(s[i].getPerimeter());
}
}
break;
case 6: for(int i=0; i<s.length; i++)
{
System.out.println(s[i].getArea());
}
break;
case 7: //Enter scale factor
//No need for a case 8 since while loop terminates it.
default: System.out.println("Number must be 1-8");
}
}
}
Here is the main method
public static void main(String args[])
{
Menu m;
do
{
Menu.display_menu();
m = new Menu(0);
}
while(m.getMenu_Select() != 8);
}
}
I have tried giving the shape array indice a fixed number and I still get a null object. I have also tried removing the for loop with the fixed indice and still get null objects.
You’re creating a new Menu object with each iteration of the loop!
Don’t do that since any changes done on this object will have no effect or memory on the next object.
Create one Menu object before the loop, and then call methods on it in the loop