汽车租赁系统预订车功能主要代码JAVA语言
时间: 2023-08-06 17:23:35 浏览: 91
java编写的租车系统代码
以下是一个简单的汽车租赁系统预订车功能的主要代码,使用JAVA语言实现:
```
import java.util.ArrayList;
public class CarRentalSystem {
private ArrayList<Car> availableCars = new ArrayList<Car>();
private ArrayList<Car> rentedCars = new ArrayList<Car>();
public CarRentalSystem(ArrayList<Car> cars) {
this.availableCars = cars;
}
public void displayAvailableCars() {
System.out.println("Available cars:");
for (Car car : availableCars) {
System.out.println(car.getDetails());
}
}
public void rentCar(int carId) {
Car car = findCar(carId);
if (car != null) {
availableCars.remove(car);
rentedCars.add(car);
System.out.println("Car " + carId + " rented successfully.");
} else {
System.out.println("Car " + carId + " not available for rent.");
}
}
public void returnCar(int carId) {
Car car = findCar(carId);
if (car != null) {
rentedCars.remove(car);
availableCars.add(car);
System.out.println("Car " + carId + " returned successfully.");
} else {
System.out.println("Invalid car ID.");
}
}
private Car findCar(int carId) {
for (Car car : availableCars) {
if (car.getId() == carId) {
return car;
}
}
for (Car car : rentedCars) {
if (car.getId() == carId) {
return car;
}
}
return null;
}
}
public class Car {
private int id;
private String make;
private String model;
private int year;
private double pricePerDay;
private boolean isAvailable;
public Car(int id, String make, String model, int year, double pricePerDay, boolean isAvailable) {
this.id = id;
this.make = make;
this.model = model;
this.year = year;
this.pricePerDay = pricePerDay;
this.isAvailable = isAvailable;
}
public int getId() {
return id;
}
public String getMake() {
return make;
}
public String getModel() {
return model;
}
public int getYear() {
return year;
}
public double getPricePerDay() {
return pricePerDay;
}
public boolean isAvailable() {
return isAvailable;
}
public String getDetails() {
return "Car ID: " + id + ", Make: " + make + ", Model: " + model + ", Year: " + year + ", Price per day: " + pricePerDay + ", Available: " + isAvailable;
}
}
```
使用方式:
1. 创建一个 `Car` 对象的数组或列表,将所有可用的车辆添加到其中。
2. 创建一个 `CarRentalSystem` 对象,将该数组或列表传递给构造函数。
3. 调用 `displayAvailableCars` 方法,显示当前可用的车辆。
4. 调用 `rentCar` 方法,传递要租赁的车辆的 ID。
5. 如果租赁成功,调用 `returnCar` 方法,传递已租赁车辆的 ID,将车辆归还。
注意:此代码仅为示例,实际系统需要更多功能和错误处理。
阅读全文