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.
- Create a local variable of type float called weight to store
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 :
-
Don’t compare booleans to
trueorfalse; they can be directly used inifstatements. (You can also combine the two if statements with the and (&&) operator.) -
Add to the sum inside the loop, not after the end.
for (float weight: weights) {
if (weight < 20 && hasLoyaltyCard) weight *= 0.95f;
totalWeight += weight;
}