Given the following code
package parkinglottest;
public class ParkingLotTest {
public static void main(String[] args) {
ParkingLot p=new ParkingLot(15);
System.out.println(p.getMax());
Car c1=new Car(1);
Car c2=new Car(2);
p.addCar(c1);//at parkinglottest.ParkingLotTest.main(ParkingLotTest.java:14)
p.addCar(c2);
}
}
package parkinglottest;
public class ParkingLot {
private int max;
public ParkingLot(int max)
{
this.max=max;
}
private Car[] cars=new Car[max];//if instead of "max" i put any other positive integer, it works just fine.
int nr=0;
public void addCar(Car c)
{
cars[nr++]=c; //at parkinglottest.ParkingLot.addCar(ParkingLot.java:17)
}
public int getMax(){
return max;
}
}
i get an ArrayIndexOutOfBoundsException.