Errornous Code
I think I've messed up the Strings/Boolean functions, but im not sure how to fix it. Any help would be appreciated.
public class Parks {
private String[] parkingBays;
private int numCars;
public Parks(int capacity) {
parkingBays = new String[numCars];
for (int i = 0; i <= parkingBays.length; i++) {
parkingBays[i] = "Empty";
}
}
public boolean park() {
String car;
if (numCars > parkingBays.length){
parkingBays[++numCars] = car;
}
else {
return false;
}
}
/**
* For Testing
*/
public static void main(String [] args) {
Parks p = new Parks(20);
boolean spaces = true;
while (spaces) {
spaces = p.park("car1");
spaces = p.park("car2");
}
for (String car : p.parkingBays)
System.out.println(car);
}
}
[1086 byte] By [
sepahs] at [2007-11-20 11:51:20]

# 1 Re: Errornous Code
You are calling your park method with a string param, which the method apparently is inteded to have, but doesnt. Suggest you place the String car as a method param, then youre all dandy.
# 2 Re: Errornous Code
Done, it compiles, although when I try to run it, I get an exception.
public class Parks {
private String[] parkingBays;
private int numCars;
public Parks(int capacity) {
parkingBays = new String[numCars];
for (int i = 0; i <= parkingBays.length; i++) {
parkingBays[i] = "Empty";
}
}
public boolean park(String car) {
if (numCars > parkingBays.length){
parkingBays[++numCars] = car;
}
else {
return false;
}
return true;
}
/**
* For Testing
*/
public static void main(String [] args) {
Parks p = new Parks(20);
boolean spaces = true;
while (spaces) {
spaces = p.park("car1");
spaces = p.park("car2");
}
for (String car : p.parkingBays)
System.out.println(car);
}
}
sepahs at 2007-11-10 2:15:02 >

# 3 Re: Errornous Code
I would suspect, that the issue is in your constructor. You have the int param, which you intend supposedly to use to assign the number of parking spaces available. However the param is not used for anything. Then when adding a new car to the parkinglot, you use a ++numcars operation, which in this particular case means that you are trying to place a value outside of your arrays index range (which is numcars, that is zero).
Even if you fix that, note that the ++numcars operation means that the first parking place will never be filled, which is probably not what you want.
Cant say much more, having no idea what your error was. Would be good, if you get an error and want info on, to actually post the error.