67.2k views
1 vote
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.

User Hkf
by
4.9k points

1 Answer

3 votes

Answer:

OrderList.java

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

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. }

Step-by-step 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.

User John S Perayil
by
4.9k points