|
Response Details:
public static void main(String[] args)
{
// a) Declare an array of type Car. The array name should be myGarage and the size of the array should be 10.
Car[] myGarage = new Car[10];
// b) Create a Car object c1 by calling the default constructor.
Car c1 = new Car();
// c) Display c1 specific data by calling the method print.
c1.print();
// d) Create a Car object c2 by calling the parameter constructor. The parameter constructor will initialize the instance variables with the following values: "Toyota", "Corolla", 2006, 15,800.
Car c2 = new Car("Toyota", "Corolla", 2007, 15800);
// e) For the Car object c2, display on the screen the values of its instance variables by invoking the get type methods.
System.out.println(c2.getMake());
System.out.println(c2.getModel());
System.out.println(c2.getYear());
System.out.println(c2.getPrice());
// f) Invite the user to input values for make, model, year and price and build the Car object c3 by invoking the constructor with parameters.
Scanner kb = new Scanner(System.in);
System.out.print("Enter the make: ");
String make = kb.nextLine();
System.out.print("Enter the model: ");
String model = kb.nextLine();
System.out.print("Enter the year: ");
int year = kb.nextInt();
System.out.print("Enter the price: ");
int price = kb.nextInt();
Car c3 = new Car(make, model, year, price);
// g) Display c3 specific data by calling method print.
c3.print();
// h) Calculate the cheapest car out of c1 and c3 and display a message showing the result.
if(c3.price() < c1.price())
{
System.out.println(c3.getMake()+" "+c3.getModel()+" is cheaper");
}
else
{
System.out.println(c1.getMake()+" "+c1.getModel()+" is cheaper");
}
// i) Calculate the most expensive car out of c2 and c3 and display a message showing the result.
if(c3.price() > c1.price())
{
System.out.println(c3.getMake()+" "+c3.getModel()+" is cheaper");
}
else
{
System.out.println(c1.getMake()+" "+c1.getModel()+" is cheaper");
}
// j) Reduce the price of c2 by 1,000 dollars.
c2.setPrice(c2.getPrice()-1000);
// k) Display c2 specific data by calling method print.
c2.print();
// l) Store c1, c2 and c3 into myGarage cells of index 0, 1 and 2 respectively.
myGarage[0] = c1;
myGarage[1] = c2;
myGarage[2] = c3;
// m) Using a loop, calculate and display the total value of all cars in myGarage.
int total = 0;
for(Car c : myGarage)
{
if(c!=null)
{
total += c.getPrice();
}
}
System.out.println(total);
}
|