4. Write part of the code that removes the car from the dealer class that is sold.
do part 4
import java.util.*;
// Car class
class Car{
private String name; // Variable to hold car name
private String model; // Variable to hold car model
// Default constructor
Car(){
this.name = null;
this.model = null;
}
// Parametrised constructor
Car(String name, String model){
this.name = name;
this.model = model;
}
// Function to get car name
public String getName(){
return this.name;
}
}
// Dealer class
class Dealer{
private Car[] arr; // Array holding car objects for a dealer
private int count; // Variable to hold number of cars under a dealer
// Default constructor
Dealer(){
arr = new Car[50];
count=0;
}
// Function to add a car under a dealer
public void addCar(Car obj){
this.arr[this.count] = obj;
this.count++;
}
// Function to check if a car exists under a dealer or not
public boolean contains(String name){
int flag=0;
for(int i=0; i<this.count; i++){
if(arr[i].getName().equals(name)){
flag=1;
break;
}
}
if(flag==1){
return true;
}
return false;
}
}
// Driver Class
public class Main
{
public static void main(String[] args) {
Dealer obj = new Dealer(); // Creating dealer class object
Car c1 = new Car("Honda","Model1"); // Creating Honda car object
Car c2 = new Car("Toyota","Model1"); // Creating Toyota car object
System.out.println("Honda car added.");
obj.addCar(c1);
System.out.println("Toyota car added.");
obj.addCar(c2);
Scanner sc = new Scanner(System.in);
System.out.println();
System.out.print("Enter the car name to be searched : ");
String name = sc.nextLine();
boolean result = obj.contains(name);
if(result==true){
System.out.println("Car is present");
}
else{
System.out.println("Car is not present");
}
}
}
Trending now
This is a popular solution!
Step by step
Solved in 2 steps