Suppose that class OrderList has a private attribute double cost[100] which hold the cost of all ordered items, and a private attributes int num_of_items which hold the number of items ordered. For example, if num_of_items is 5, then cost[0], cost[1], ..., cost[4] hold the cost of these 5 items. Implement the member function named total_cost which returns the total cost of this OrderList.

Respuesta :

Answer:

OrderList.java

  1. public class OrderList {
  2.    private double cost[];
  3.    private int num_of_items;
  4.    
  5.    public OrderList(){
  6.        cost = new double[100];
  7.    }
  8.    public double total_cost(){
  9.        double total = 0;
  10.        for(int i=0; i < num_of_items; i++){
  11.            total += cost[i];
  12.        }
  13.        return total;
  14.    }
  15. }

Main.java

  1. public class Main {
  2.    public static void main(String[] args) {
  3.        OrderList sample = new OrderList();
  4.        double totalCost = sample.total_cost();
  5.    }
  6. }

Explanation:

Firstly, define a class OrderList with two private attributes, cost and num_of_items (Line 1-3). In the constructor, initialize the cost attribute with a double type array with size 100. Next, create another method total_cost() to calculate the total cost of items (Line 9-15). To implement the total_cost member function, create an OrderList instance and use that instance to call the total_cost() and assign it to totalCost variable.