0

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?

Jack
  • 1,339
  • 1
  • 12
  • 31
  • Can you add code for `warehouse` class and the other methods being used in the code. – Tarun Kolla Nov 30 '19 at 04:42
  • double/int was answered [here](https://stackoverflow.com/questions/13297207/is-it-valid-to-compare-a-double-with-an-int-in-java). There's something about Double/Double [here](https://stackoverflow.com/questions/45878215/is-comparing-double-values-using-deterministic) – Curiosa Globunznik Nov 30 '19 at 04:50
  • This would probably be easy to debug by adding logging. In method-2 at the end of the loop, print all variables in the compare. – AndyMan Nov 30 '19 at 04:51
  • 1
    I'd propose to debug by using a [debugger](https://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me-diagnose-problems?noredirect=1&lq=1). – Curiosa Globunznik Nov 30 '19 at 04:52
  • thanks for comments. So you think both the comparison method is ok? there could be issues elsewhere outside the while loop? – Jack Nov 30 '19 at 05:30

0 Answers0