Skip to main content

Practice Code Structure

Section 1.39 Code Comprehension

Activity 1.39.1.

    Look at the first code block. Which of the following options have the same functionality as it (i.e., they produce the same output for the same inputs)? You can check the Hint for some input examples.
    public static double calculatePrice(double price, boolean isHoliday, boolean isClearance) {
      if (isHoliday) {
        return price - (price * 0.10);
      } else if (isClearance) {
        return price - (price * 0.20);
      } else {
        return price;
      }
    }
    
    Hint.
    You can use the following test cases to compare the code blocks’ functionality.
    • calculatePrice(120, true, true)
    • calculatePrice(100, true, false)
    • calculatePrice(100, false, true)
    Select all that apply.
  • public static double calculatePrice(double price, boolean isHoliday, boolean isClearance) {
      double discountRate;
      if (isHoliday) {
         discountRate = 0.10;
      } else if (isClearance) {
         discountRate = 0.20;
      } else {
         discountRate = 0.0;
      }
      return price * (1- discountRate);
    }
    
  • Correct!
  • public static double calculatePrice(double price, boolean isHoliday, boolean isClearance) {
      double finalPrice;
      if (isHoliday) {
        finalPrice = price - (price * 0.10);
      } else if (isClearance) {
        finalPrice = price - (price * 0.20);
      } else {
        finalPrice = price;
      }
      return finalPrice;
    }
    
  • Correct!
  • public static double calculatePrice(double price, boolean isHoliday, boolean isClearance) {
      double discountRate = 0.0;
      if (isHoliday) {
        discountRate = 0.10;
      } else if (isClearance) {
        discountRate = 0.20;
      }
      return price * (1- discountRate);
    }
    
  • Correct!
  • public static double calculatePrice(double price, boolean isHoliday, boolean isClearance) {
      double discountRate = 0.0;
      if (isClearance) {
        discountRate = 0.20;
      } else if (isHoliday) {
        discountRate = 0.10;
      }
      return price * (1- discountRate);
    }
    
  • Not always! Code block in option D does not have the same functionality with the first code block! Compare the outputs for calculatePrice(100, true, true)
You have attempted 1 of 2 activities on this page.