Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

  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;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading