I am simulating a truck loading parcels from a warehouse. I have a problem of truck being over loaded. I have tried two ways but the truck will always load more than it's capacity. I think this is due to the comparison method between double and int (method-1), or comparison between double and double (method-2)
load_wgt (truck) and next.getWgt (parcel) are double variables. capacity (truck) is an integer.
method-1:
while ((int) Math.ceil((this.load_wgt + next.getWgt())) <= this.capacity) {
this.load_list.add(next);
this.setLoad_wgt(this.load_wgt + next.getWgt());
warehouse.remove(next);
next.setTruck_id(this.id);
System.out.println("parcel id " + next.getId() + " truck id " + this.id);
next = warehouse.get(0);
}
method-2:
while (compare <= 0) {
this.load_list.add(next);
this.setLoad_wgt(this.load_wgt + next.getWgt());
warehouse.remove(next);
next.setTruck_id(this.id);
System.out.println("parcel id " + next.getId() + " truck id " + this.id);
next = warehouse.get(0);
compare = Double.compare(this.load_wgt + next.getWgt(), (double) this.capacity);
}
How to make sure the loading of the next parcel will not exceed the truck's capacity? What is the right way to compare between doubles or between a double and a int?