Skip to main content

Practice Code Structure

Section 1.42 Identification

Activity 1.42.1.

    These code blocks are the ones you saw in the previous question and they all have the same functionality. Among these options which one is preferable?
  • public static double calculateWeight(double weight, boolean isFragile, boolean isBulk) {
    	if (isFragile) {
    		return weight + (weight * 0.1);  // Add 10% extra for packaging
    	}
    	else if (isBulk) {
    		return weight + (weight * 0.05);  // Add by 5% for bulk items
    	} else {
    		return weight;
    	}
    }
    
  • This code can be improved!
  • public static double calculateWeight(double weight, boolean isFragile, boolean isBulk) {
    	double adjustment = 0.0;
    	if (isFragile) {
    		adjustment += 0.1;  
    	} else if (isBulk) {
    		adjustment += 0.05;  
    	}
    	return weight * (1 + adjustment);
    }
    
  • Correct!
  • public static double calculateWeight(double weight, boolean isFragile, boolean isBulk) {
    	double finalWeight = weight;
    	if (isFragile) {
    		finalWeight += weight * 0.1;
    	} else if (isBulk) {
    		finalWeight += weight * 0.05;
    	}
    	return finalWeight;
    }
    
  • This code can be improved!
You have attempted 1 of 2 activities on this page.