Home > Blockchain >  I am struggling with a for loop for an array. How do I fix my java code?
I am struggling with a for loop for an array. How do I fix my java code?

Time:01-10

So I am stuck on this problem I am trying to complete.

I need to make a for loop that takes weights from an array and updates them if they meet certain conditions. If the weight in the array is under 20, and a customer has a loyalty card (both have to be true), then the weight would be reduced down to 95% of the initial weight (0.95 * weight). Then add the weights together.

Anyways, here's the problem and my answer:

Between the two comments, do the following:

  • Create a for loop that goes through the whole weights array.
  • Within the for loop, do the following:
    • Create a local variable of type float called weight to store the value of weights at a specific index.
    • Create a conditional that checks whether weight is under 20 and whether hasLoyaltyCard is true and multiply weight by 0.95 if it is.
    • Add weight to totalWeight the variable.
float calculateWeight(float[] weights, boolean hasLoyaltyCard) {
        float totalWeight = 0;
        // TODO: Step 1 work goes between the two comments 
        float weight = 0;
        for (int i = 0; i < weights.length; i  ) {
            weight = weights[i];
            if (weight < 20.0) {
                if (hasLoyaltyCard = true) { 
                    weight = weight * 0.95f;
                }
            }    
            totalWeight = totalWeight   weight;
        }
        //
        return totalWeight;
    }

I'm just not sure where I went wrong. The code does compile, fortunately. But when running test cases, they aren't correct. Where is my mistake?

CodePudding user response:

  1. Don't compare booleans to true or false; they can be directly used in if statements. (You can also combine the two if statements with the and (&&) operator.)

  2. Add to the sum inside the loop, not after the end.

for (float weight: weights) {
    if (weight < 20 && hasLoyaltyCard) weight *= 0.95f;
    totalWeight  = weight;
}

CodePudding user response:

Keep the totalWeight = totalWeight weight; in the for loop as shown below and change the if condtion

for (int i = 0; i < weights.length; i  ) {
            weight = weights[i];
            if (weight < 20.0) {
                if (hasLoyaltyCard) { 
                    weight = weight * 0.95f;
                }
            }
            totalWeight = totalWeight   weight;
        }    
  • Related