I need help with this piece of code.
public class ParkingLot {
static int MAX = 5;
static Car[] Slot = new Car[MAX];
public static void main(String[] args) {
Slot[0] = new Car("1234", "White");
Slot[1] = new Car("5678", "Black");
}
public static void Allot() {
for (int i = 0; i <= Slot.length; i++) {
System.out.println(Slot.getNo);
}
}
I am storing a Car Object in Slot. I wish to print/access the No and Colour of the car stored in slot. How do I go about doing that?
Well, if
carhas a public property, or a public getter method (this is preferable –getNumber()andgetColour()), you can call them while iterating the array with the for-each loop:Note that I’ve lowercased
slot– variable names in Java should be lowercase. I’d also advise for naming the array with plural name – i.e.slots.Note also that the way of iteration provided by others is possible, but not recommended for the basic case of iterating the whole array. Effective Java (Bloch) recommends using the foreach loop whenever possible.