现在我正在做涉及形状类的经典形状程序。我可以毫无问题地创建圆形或矩形对象。但是当我得到所有对象的周长或面积时,结果发现所有对象都是空的。这是代码:
//案例菜单选择动作
这里是实例变量和数组
private int menu_select;
private int i=0;
private Shape[] s = new Shape[10];
这是菜单选项
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");
}
这是菜单代码
这里是开关
//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");
}
}
}
这里是主要方法
public static void main(String args[])
{
Menu m;
do
{
Menu.display_menu();
m = new Menu(0);
}
while(m.getMenu_Select() != 8);
}
}
我尝试给形状数组索引一个固定的数字,但我仍然得到一个空对象。我还尝试使用固定索引删除 for 循环,但仍然得到空对象。