我的计数器工作不正常。该方法接受汽车添加到停车库阵列中。停车场最多只能容纳10辆车,但是当我运行我的程序时,它只允许最多5辆车,即使我有10个设置为阵列的SIZE。
//instance variables.
private Car automobiles[]; //Array List of Cars
private int counter = 0; //counter to keep track of cars in garage.
private Car toyota; // car object
private static final int SIZE = 10;
public String arrive(Car next)
{
toyota = next;
if (counter < SIZE) // checks to make sure the garage is not full
{
automobiles[counter] = toyota; //parks new car into garage
counter++;
return "" + toyota.getlicenseNumber() + " has been parked.\n";
}
else // else statement if garage is full
{
return "Sorry, " + toyota.getlicenseNumber()
+ " cannot be parked. The Parking lot is Full!!";
}
}
这是我的输出
JAV001 has been parked.
JAV002 has been parked.
JAV003 has been parked.
JAV004 has been parked.
JAV005 has been parked.
Sorry, JAV006 cannot be parked. The Parking lot is Full!!
Sorry, JAV007 cannot be parked. The Parking lot is Full!!
Sorry, JAV008 cannot be parked. The Parking lot is Full!!
Sorry, JAV009 cannot be parked. The Parking lot is Full!!
Sorry, JAV0010 cannot be parked. The Parking lot is Full!!
答案 0 :(得分:2)
private static final int SIZE = 10;
您已将SIZE
设为static/Class variable
和
private int counter = 0;
counter
为instance variable
。
因此,即使您在一个车库实例中最多需要10辆车,因为您宣布SIZE为静态,您的所有车库实例中最多可以有10辆车。因此,如果您之前的实例有5辆汽车,那么只允许5辆汽车。您可能希望将SIZE设置为实例变量。
private final int SIZE = 10;