import java.io.
*;
import java.util.Scanner;
// Define the Car class
class Car implements Serializable {
private String name;
private double price;
private int speed;
// Constructor
public Car(String name, double price, int speed) {
this.name = name;
this.price = price;
this.speed = speed;
}
// Getters
public String getName() {
return name;
}
public double getPrice() {
return price;
}
public int getSpeed() {
return speed;
}
@Override
public String toString() {
return "Car{name='" + name + '\'' + ", price=" + price + ", speed=" + speed
+ '}';
}
}
public class Showroom {
private static final String FILE_NAME = "Showroom.dat";
public static void main(String[] args) {
try {
// Create three Car objects
Car car1 = new Car("Toyota", 25000, 180);
Car car2 = new Car("Honda", 23000, 200);
Car car3 = new Car("BMW", 55000, 240);
// Create an array of Car objects
Car[] cars = {car1, car2, car3};
// Save these objects to a file
saveCarsToFile(cars); // Pass the array instead of varargs
// Search for a car
search();
} catch (IOException e) {
System.err.println("Error during file operations: " + e.getMessage());
} catch (ClassNotFoundException e) {
System.err.println("Error: Class not found during deserialization: " +
e.getMessage());
}
}
// Save Car objects to a file
private static void saveCarsToFile(Car[] cars) throws IOException {
try (ObjectOutputStream oos = new ObjectOutputStream(new
FileOutputStream(FILE_NAME))) {
for (Car car : cars) {
oos.writeObject(car);
}
System.out.println("Cars have been saved to the file.");
}
}
// Search for a car in the file
private static void search() throws IOException, ClassNotFoundException {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the name of the car to search: ");
String searchName = scanner.nextLine();
try (ObjectInputStream ois = new ObjectInputStream(new
FileInputStream(FILE_NAME))) {
boolean found = false;
while (true) {
try {
Car car = (Car) ois.readObject();
if (car.getName().equalsIgnoreCase(searchName)) {
System.out.println("Car found: " + car);
found = true;
break;
}
} catch (EOFException e) {
break; // End of file reached
}
}
if (!found) {
System.out.println("Car with name '" + searchName + "' not
found.");
}
}
}
}