Question

I am implementing a programm that creates and vehicle manager, with vehicle(objects) and those vehicle objects contain booking objects (with two Strings, one for the beginning date, and one for the end date) So I did some booking tests and it doesnt work. It must be in this method.

    public boolean isBookable(Booking wishedBooking) {

    boolean bookable = false;

    if ((wishedBooking.begin.compareTo(begin) != 1
            && wishedBooking.end.compareTo(begin) != 1)
            || (wishedBooking.begin.compareTo(end) != -1
                && wishedBooking.end.compareTo(end) != -1)) {
        bookable = true;
    }

    return bookable;             
}

What I tried to do is to use compareTo. The dates have the format: YYYY/MM/DD HH:MM

So the only way the attempt booking can be done is when the begining and end of it is bellow or above one of the booking. If in one case it is not like that, it means that it cant be booked since at one time period of the time interval, there is already a booking. I am using != because it is possible that it can be equal, so the result will be 0.

The vehicle object now iterated with an methode over all the booking objects to check whether the booking can be done, os it is bookable.

Where is the mistake?

Was it helpful?

Solution

The contract of a.compareTo(b) is to return a value greater than 0 if a is "larger" than b, a value smaller than 0 if it's "smaller" or 0 if they are equal. Using 1 and -1 is purely an implementation detail, and you should not rely on it. I.e., your should change your code to:

public boolean isBookable(Booking wishedBooking) {

    boolean bookable = false;

    if ((wishedBooking.begin.compareTo(begin) <= 0
            && wishedBooking.end.compareTo(begin) <= 0)
            || (wishedBooking.begin.compareTo(end) >= 0
                && wishedBooking.end.compareTo(end) >= 0)) {
        bookable = true;
    }

    return bookable;             
}

Note that since you're only returning a boolean, the if can be removed, and you can just return its condition:

public boolean isBookable(Booking wishedBooking) {
    return ((wishedBooking.begin.compareTo(begin) <= 0
            && wishedBooking.end.compareTo(begin) <= 0)
            || (wishedBooking.begin.compareTo(end) >= 0
                && wishedBooking.end.compareTo(end) >= 0));
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top