You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java租车系统:同车同日不重复租赁方法的实现问题排查

修复租车方法的重复租赁校验问题

问题分析

当前carRental方法的错误在于错误地试图访问RentalCars类不存在的rentDate和UCI属性来判断车辆是否已被租赁,正确的校验逻辑应该基于传入的RentTransactions对象集合——通过检查该集合中是否存在同一车辆+同一租赁日期的记录来避免重复租赁。

解决方案

重新实现carRental方法,通过遍历RentTransactions集合完成合法性校验,具体步骤:

  • 接收参数:目标RentalCars车辆、DateOfRenting租赁日期、Customers客户、RentTransactions交易记录集合
  • 校验逻辑:检查交易记录中是否存在与当前车辆匹配,且租赁日期相同的记录
  • 校验通过则创建新的租赁交易并添加到集合;不通过则抛出异常或返回错误提示

代码示例

假设各类的核心属性如下:

  • RentalCars:carId(车辆唯一标识)
  • DateOfRenting:date(租赁日期,可直接比较或转为统一格式)
  • RentTransactions:rentedCar(关联的RentalCars对象)、rentDate(关联的DateOfRenting对象)、customer(关联的Customers对象)

修复后的carRental方法(以Java为例):

public boolean carRental(RentalCars targetCar, DateOfRenting rentDate, Customers customer, List<RentTransactions> transactions) {
    // 校验是否存在重复租赁记录
    boolean isAlreadyRented = transactions.stream()
        .anyMatch(t -> t.getRentedCar().getCarId().equals(targetCar.getCarId())
                && t.getRentDate().getDate().equals(rentDate.getDate()));
    
    if (isAlreadyRented) {
        System.out.println("该车辆在指定日期已被租赁");
        return false;
    }
    
    // 校验通过,创建新的租赁交易
    RentTransactions newTransaction = new RentTransactions();
    newTransaction.setRentedCar(targetCar);
    newTransaction.setRentDate(rentDate);
    newTransaction.setCustomer(customer);
    transactions.add(newTransaction);
    
    System.out.println("租车成功");
    return true;
}

关键说明

  • 核心校验逻辑依赖RentTransactions的历史记录,而非RentalCars本身的属性,完全符合需求中“通过传入的RentTransactions对象属性完成合法性校验”的要求
  • 需确保RentalCars有唯一标识属性(如carId)、DateOfRenting有可准确比较的日期属性,保证校验逻辑的正确性

内容的提问来源于stack exchange,提问作者PoeticSonic

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 11:50:34