21xrx.com
2024-09-20 05:55:02 Friday
登录
文章检索 我的文章 写文章
Java编写租车系统:一个实用的案例
2023-06-18 06:58:04 深夜i     --     --
Java编程 租车系统 数据结构

租车系统是许多公司和个人都需要的一个应用。基于Java语言的优势,可以轻松地编写一个完整的租车系统。

以下是一个简单的代码实现,用于展示如何使用Java编写租车系统。

首先,我们需要定义一些基本的数据结构:


public enum CarType

  SEDAN

public class Car

  private String id;

  private CarType carType;

  private boolean available;

  // constructor

public class Customer

  private String id;

  private String name;

  private String phone;

  // constructor

public class Rental

  private String id;

  private Customer customer;

  private Car car;

  private LocalDate rentalDate;

  private int days;

  private double price;

  // constructor

接下来,我们需要一个代表租车公司的类:


public class CarRentalCompany {

  private List cars;

  private List rentals;

  // constructor, getters and setters

  public Rental rentCar(CarType carType, Customer customer, int days) {

    Car car = findAvailableCar(carType);

    if (car == null)

      return null;

    

    car.setAvailable(false);

    Rental rental = new Rental(generateRentalId(), customer, car, LocalDate.now(), days, calculatePrice(carType, days));

    rentals.add(rental);

    return rental;

  }

  private Car findAvailableCar(CarType carType) {

    return cars.stream().filter(car -> car.getCarType() == carType && car.isAvailable()).findFirst().orElse(null);

  }

  private String generateRentalId() {

    return UUID.randomUUID().toString();

  }

  private double calculatePrice(CarType carType, int days)

    // pricing strategy based on car type and number of days rented

  

}

我们可以使用上述代码来实现一个简单的租车系统。下面是一个使用示例:


CarRentalCompany company = new CarRentalCompany(Arrays.asList(

    new Car("C1", CarType.SEDAN, true),

    new Car("C2", CarType.SUV, true),

    new Car("C3", CarType.HATCHBACK, true),

    new Car("C4", CarType.CONVERTIBLE, true)

), new ArrayList<>());

Customer customer = new Customer("CUSTOMER1", "John Doe", "555-1234");

Rental rental = company.rentCar(CarType.SEDAN, customer, 3);

在上面的示例中,我们首先创建了一个包含四辆车的租车公司对象。然后,我们创建了一个代表客户的对象。最后,我们使用`rentCar()`方法租了一辆轿车,将租车信息保存到租赁列表中。

本文展示了如何使用Java编写一个简单的租车系统,使用多个类和枚举。我们可以根据实际要求对其进行扩展以实现更复杂的功能。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复