Skip to main content

Practice Code Structure

Section 1.44 Identification

Activity 1.44.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 void displayDiscount(String customerType, double price) {
       double finalPrice = 0;
    
       if ("VIP".equals(customerType)) {
           finalPrice = price * 0.8; 
           System.out.println("Customer Type: VIP");
           System.out.println("Original Price: $" + price);
           System.out.println("Discounted Price: $" + finalPrice);
       } else if ("Regular".equals(customerType)) {
           finalPrice = price * 0.9; 
           System.out.println("Customer Type: Regular");
           System.out.println("Original Price: $" + price);
           System.out.println("Discounted Price: $" + finalPrice);
       } else {
           finalPrice = price;  
           System.out.println("Customer Type: Guest");
           System.out.println("Original Price: $" + price);
           System.out.println("Discounted Price: $" + finalPrice);
       }
    }
    
  • This code can be improved!
  • public static void displayDiscount(String customerType, double price) {
       double finalPrice = price;
    
       if ("VIP".equals(customerType)) {
           finalPrice = price * 0.8;  
           System.out.println("Customer Type: VIP");
       } else if ("Regular".equals(customerType)) {
           finalPrice = price * 0.9; 
           System.out.println("Customer Type: Regular");
       } else {
           System.out.println("Customer Type: Guest");
       }
    
       System.out.println("Original Price: $" + price);
       System.out.println("Discounted Price: $" + finalPrice);
    }
    
  • This code can be improved further!
  • public static void displayDiscount(String customerType, double price) {
       double adjustedPriceFactor = 1;
    
       if ("VIP".equals(customerType)) {
           adjustedPriceFactor = 0.8; 
           System.out.println("Customer Type: VIP");
       } else if ("Regular".equals(customerType)) {
           adjustedPriceFactor = 0.9;  
           System.out.println("Customer Type: Regular");
       } else {
           System.out.println("Customer Type: Guest");
       }
       
       double finalPrice = price * adjustedPriceFactor;  
       System.out.println("Original Price: $" + price);
       System.out.println("Discounted Price: $" + finalPrice);
    }
    
  • Correct!
You have attempted 1 of 2 activities on this page.