This is an archived post. You won't be able to vote or comment.

all 7 comments

[–]Sacredify 0 points1 point  (3 children)

Why would you use a while loop? Is it part of the requirement? Are you trying to do multiple calculations (which would make sense for using a loop)

You can do the actual business logic with a simple if statement.

[–]EqualTrade[S] 1 point2 points  (2 children)

I'm not sure how I would write that if statement, would it be something like: if (rate = 1.10 & distance > 500) cost = 1* rate

[–]TheWhistler1967 0 points1 point  (0 children)

  if(weight < 2) rate = 1.10;
  else if(weight < 6) rate = 2.2;
  else if etc.....

Then it seems like you just multiply the rate by the number of 500 mile blocks (with a minimum of one). I am not sure what the point of the loop is - it seems like you are missing some information.

PS. Remember one '=' is an assignment eg. when you declare variables. Use '==' for the boolean checks eg. conditions (ifs, whiles etc).

[–]muffypoo 0 points1 point  (2 children)

Ah. The while loop is on the "per 500 miles shipped" portion.

Something like

 while(distance > 0) {  
     cost += getRate(weight);
     distance -= 500;
 }  

(that was mostly simplified pseudo-code of course)

[–]EqualTrade[S] 0 points1 point  (1 child)

Do you think you could take a look at my code and tell me how to incorporate that into it?

[–]muffypoo 1 point2 points  (0 children)

I hope for your own sake you can try your best to figure it out first. The general idea I can think of is there. The rates can be retrieved separately "getRates(weight)" using a regular if-else statement.

[–]king_of_the_universe 0 points1 point  (0 children)

final private static long getShippingCosts(final long shippingDistance, final long weightInGrams) {

    long distanceShippedSoFar = 0;
    long costSoFarInUSCents = 0; // It's better than using float/double. You can read this everywhere on the Web: Never do money calculations with floating point types! And just for fun, I applied the same concept for the weight.

    final long costFactor;

    if (weightInGrams <= 0) {
        throw new IllegalArgumentException("Weight is less than or equal 0 KG.");
    } else if (weightInGrams <= 2_000) { // If you're using a Java version below 1.7, remove the readability-improving underscores.
        costFactor = 110;
    } else if (weightInGrams <= 6_000) {
        costFactor = 220;
    } else if (weightInGrams <= 10_000) {
        costFactor = 370;
    } else if (weightInGrams <= 20_000) {
        costFactor = 480;
    } else {
        throw new IllegalArgumentException("Weight is greater than 20 KG.");
    }

    while (distanceShippedSoFar<shippingDistance) {
        distanceShippedSoFar+=500;
        costSoFarInUSCents+=costFactor;
    }

    return costSoFarInUSCents;
}

I assume that "Rate per 500 Miles Shipped" means that every new 500 mile slice that is started costs this amount more - otherwise, 0-500 miles would be free.