Domanda

I have a homework for one of my university courses (Special Java Chapters - to be more specific). I have to do a program which has to simulate a car configurator - so i have two car models from a manufacturer , each car has a fixed price and multiple options. Each option can have a description and a price (ex: engine - price/HP/cm3/fuelCons) . I decided to make two classes : one for the model with name and final price and another class for options with multiple inherited classes for each option in part.

In the end i have to make a menu so each customer can be able to add or remove any option (an aleardy added one) and show the final price --something like this (it's about the same brand).

I don't know exactly how to do that menu.

È stato utile?

Soluzione

As 'Options' can have several abilities, a native type is not enough. Therefore you have to create another class 'Option' and add fields like description, price, title, etc.

class Option {
    private String description;
    private double price;
    ...
}

Create a class Car or CarModel to put in the title, etc and add a list of options:

class Car {
  ...
     private final double FIXED_PRICE;
  ...
     List<Option> options = new ArrayList<Option>();
  ...
     public Car(final double price) {
       this.FIXED_PRICE  = price;
     }
}

To make a price a constant is very uncommon, but maybe ok in our case. To assign a final field at class initializaiton you need to add a constructor like that one shown above.

You also need to add methods for adding and removing options:

public void addOption(Option option) {...}
public void removeOption(Option option) {...}

If a type of Option can only exist once in your options list you can make it a Set. To calculate the final price add a method that is iterating your options list and summing the prices with the fixed price from the car.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top