tomaszsvd tomaszsvd - 18 days ago 12
Java Question

Longest parked vehicle

I have arrayList of objects:

private ArrayList<Vehicle> vehicles = new ArrayList<>()


When user inputs all the details to add vehicle, he inputs the date and time:

Example Input:

Enter date: DD/MM/YYYY

13/11/2016

Enter time: HH:MM

10:00


The array has capacity of 20 objects so there is more than one input, the date and time are inputed as strings. How do I display the vehicle that was parked the longest time? I have something like this but it wont work at all.

long longest = 0;
for (Vehicle vehicle : vehicles){
long hours = vehicle.getDateTime().hours();
if (hours > longest){
longest = hours;

}

}

Answer

Print the longest outside the loop, not everytime you find a longer one

    long longest =  Long.MIN_VALUE;
    Vehicle v = null;
    for (Vehicle vehicle : vehicles){
        long hours = vehicle.getDateTime().hours();
        if (hours > longest){
            longest = hours; 
            v = vehicle;
        }
    }

    if (v!=null) {
        System.out.println("Longest Parked Vehicle is:");
        System.out.println(v);
    } 

And, implement a toString method for the Vehicle class!

Comments