java 计算一次租赁多辆汽车的总租金
时间: 2023-05-14 22:00:55 浏览: 154
在Java中计算一次租赁多辆汽车的总租金可以通过以下步骤实现:
1. 定义汽车对象和租车信息类:首先需要定义一个汽车对象类,其中包括汽车品牌、租金/天、数量等属性;然后定义一个租车信息类,包括租车天数、租车数量、所租汽车类型等属性。
2. 获取租车信息:通过用户输入或者从数据库中获取租车信息,对租车信息类进行赋值。
3. 计算租车总费用:根据所租车辆类型和租车天数计算每辆车的租车费用,然后将各辆车的租车费用相加得出总租金。
4. 输出计算结果:将计算得出的总租金打印输出,或者将其存入数据库等方便用户查看。
代码实现的一个例子如下所示:
public class Car {
String brand;
int rentPrice;
int amount;
public Car(String brand, int rentPrice, int amount) {
this.brand = brand;
this.rentPrice = rentPrice;
this.amount = amount;
}
}
public class RentCar {
int days;
int num;
Car car;
public RentCar(int days, int num, Car car) {
this.days = days;
this.num = num;
this.car = car;
}
public int getTotalFee() {
return this.days * this.num * this.car.rentPrice;
}
}
public class RentTest {
public static void main(String[] args) {
Car car1 = new Car("Audi", 500, 3);
Car car2 = new Car("BMW", 600, 2);
RentCar rentCar1 = new RentCar(5, 2, car1);
RentCar rentCar2 = new RentCar(7, 1, car2);
int totalFee = rentCar1.getTotalFee() + rentCar2.getTotalFee();
System.out.println("总租金为:" + totalFee);
}
}
在上述代码中,我们定义了Car类和RentCar类,其中Car类记录了汽车的品牌、租金和数量,RentCar类记录了租车天数、租车数量和租用的汽车类型。在RentTest类中,我们创建了两个Carbon类型的实例对象,并计算了总租金。最后输出总租金即可。