Search code examples
javarounding

Shipping Charges Calculator in Java, coming up with wrong figures


I am using Java and doing a shipping charges calculator based on different weights and distances. We are practicing the if-else statements but I am running into a problem I can't figure out.

When I calculate different weights and distances I am getting the wrong answers.

I think it has something to do with my math where I can't seem to get the program to add the next charge for distance because it's not using the remainder. Please help me understand this.

public class ShippingCharges {

private double weight;
private double miles;


public ShippingCharges (double w, double m)
{
    weight = w;
    miles = m;
}


public double getShippingCharges()
{
    double charges;
    if (weight <= 2.0)
    { charges = (1.10 * miles / 500);
    }
    else if ((weight > 2.0) && (weight <= 6.0))
    {
        charges = (2.20 * (miles  / 500 ));
    }
    else if ((weight > 6.0) && (weight <=10.0))
    {
        charges = (3.70 * (miles / 500 )); 
    }
    else 
    {
        charges = (4.80 * miles  / 500);
    }
    return charges;
    
    }
}

Solution

  • From what you said I understand the problem is you are not rounding up the miles/500 result, try this:

    public double getShippingCharges()
    {
        double charges;
        if (weight <= 2.0)
        { charges = (1.10 * Math.ceil(miles / 500));
        }
        else if ((weight > 2.0) && (weight <= 6.0))
        {
            charges = (2.20 * Math.ceil(miles  / 500 ));
        }
        else if ((weight > 6.0) && (weight <=10.0))
        {
            charges = (3.70 * Math.ceil(miles / 500 )); 
        }
        else 
        {
            charges = (4.80 * Math.ceil(miles  / 500));
        }
        return charges;
    
        }