JAVA实现按借出时间和归还时间和价格计算费用
时间: 2023-07-27 22:07:03 浏览: 54
假设我们有一个 Book 类,其中包含借出时间、归还时间和价格等属性。按照借出时间和归还时间计算费用的话,可以使用以下方法:
```java
public class Book {
private Date borrowTime; // 借出时间
private Date returnTime; // 归还时间
private double price; // 价格
// 构造方法
public Book(Date borrowTime, Date returnTime, double price) {
this.borrowTime = borrowTime;
this.returnTime = returnTime;
this.price = price;
}
// 计算费用的方法
public double calculateFee() {
long borrowMillis = borrowTime.getTime();
long returnMillis = returnTime.getTime();
long durationMillis = returnMillis - borrowMillis; // 借阅时长(毫秒)
// 将毫秒转换为小时数
double durationHours = durationMillis / (1000.0 * 3600);
// 计算费用
double fee = durationHours * price;
return fee;
}
}
```
上述代码中,我们首先定义了一个 Book 类,并在类中定义了借出时间、归还时间和价格等属性。在类中还定义了一个 calculateFee() 方法,用于计算费用。
在 calculateFee() 方法中,我们首先通过 borrowTime 和 returnTime 属性计算出借阅时长(以毫秒为单位),然后将毫秒转换为小时数。最后,我们将借阅时长乘以价格,即可得到总费用。
使用示例:
```java
// 假设借出时间为 2021-01-01 08:00:00,归还时间为 2021-01-02 10:30:00,价格为 1.5 元/小时
Date borrowTime = new Date(2021 - 1900, 0, 1, 8, 0, 0);
Date returnTime = new Date(2021 - 1900, 0, 2, 10, 30, 0);
double price = 1.5;
Book book = new Book(borrowTime, returnTime, price);
double fee = book.calculateFee();
System.out.println("费用为:" + fee + " 元");
```
输出结果:
```
费用为:33.0 元
```
按照价格计算费用的话,可以在 Book 类中增加一个 calculateFee(double hours) 方法,用于根据借阅时长和价格计算费用。示例如下:
```java
public class Book {
// ...
// 根据借阅时长和价格计算费用的方法
public double calculateFee(double hours) {
double fee = hours * price;
return fee;
}
}
```
使用示例:
```java
// 假设借出时间为 2021-01-01 08:00:00,归还时间为 2021-01-02 10:30:00,价格为 1.5 元/小时
Date borrowTime = new Date(2021 - 1900, 0, 1, 8, 0, 0);
Date returnTime = new Date(2021 - 1900, 0, 2, 10, 30, 0);
double price = 1.5;
Book book = new Book(borrowTime, returnTime, price);
long borrowMillis = book.getBorrowTime().getTime();
long returnMillis = book.getReturnTime().getTime();
long durationMillis = returnMillis - borrowMillis; // 借阅时长(毫秒)
// 将毫秒转换为小时数
double durationHours = durationMillis / (1000.0 * 3600);
double fee = book.calculateFee(durationHours);
System.out.println("费用为:" + fee + " 元");
```
输出结果:
```
费用为:33.0 元
```