I got this function which is a private boolean function that checks if there is a car already of the same size inside the garage. If there isn’t I add it to the arrayList, I’ve made a printList() type function before to traverse through the arraylist and print out the values (which works perfectly) but somehow my private boolean function doesnt seem to work at all.
Heres my code:
public class Cars {
public Cars (String size, boolean booking) {
this.carSize = size;
this.isBooked = booking;
}
public String getSize() {
return this.carSize;
}
public boolean checkBook () {
return this.isBooked;
}
private String carSize;
private boolean isBooked;
}
public class Locations {
public Locations (String curLocation) {
garage = new ArrayList<Cars>();
location = curLocation;
}
public void addCar (String size, boolean booking) {
if (garage.isEmpty() || !checkCar(size)) {
garage.add(new Cars(size, booking));
System.out.println("Car assigned " + location + " " + size);
}
}
private boolean checkCar (String size) {
for (Cars car : garage) {
System.out.println("hey");
if (size.equals(car.getSize())) return true;
}
return false;
}
private ArrayList <Cars> garage;
private String location;
}
The input is as the following:
Car small City
Car small Redfern
Car small Redfern
output:
Car assigned City small
Car assigned Redfern small
Car assigned Redfern small
it should never print out the second Redfern small, as there already is that size car inside the list.
(My previous answer was wrong – I misread the code in my haste …)
I can think of only one explanation for what is going on:
This would explain why you are seeing the message
Car assigned Redfern smalltwice, and why you are NOT seeinghey.You can confirm this by putting a traceprint in the
Locationsconstructor …The theory that this is caused by leading / trailing whitespaces on one of the
sizestrings doesn’t hold water. If that was the problem, the OP would seeheyas thecheckCarmethod iterated thegaragelist.