汽车出租系统java运用数组,继承
时间: 2023-08-18 22:05:11 浏览: 109
Java实现汽车租赁系统
好的,这是一个简单的汽车出租系统Java程序的示例,使用了继承和数组。
首先,我们定义一个Car类来表示汽车:
```java
public class Car {
private String make;
private String model;
private int year;
private double price;
public Car(String make, String model, int year, double price) {
this.make = make;
this.model = model;
this.year = year;
this.price = price;
}
public String getMake() {
return make;
}
public String getModel() {
return model;
}
public int getYear() {
return year;
}
public double getPrice() {
return price;
}
public String toString() {
return year + " " + make + " " + model + ", $" + price;
}
}
```
然后,我们定义一个RentalCar类来表示出租汽车,它继承自Car类:
```java
public class RentalCar extends Car {
private boolean rented;
public RentalCar(String make, String model, int year, double price) {
super(make, model, year, price);
rented = false;
}
public boolean isRented() {
return rented;
}
public void rent() {
rented = true;
}
public void returnCar() {
rented = false;
}
public String toString() {
String status;
if (rented) {
status = " (rented)";
} else {
status = " (available)";
}
return super.toString() + status;
}
}
```
在RentalCar类中,我们添加了一些特定于租车的方法,如rent()和returnCar(),并添加了一个表示是否已被租赁的变量rented。
现在,我们可以创建一个CarRentalSystem类,用于管理所有的租车:
```java
import java.util.Scanner;
public class CarRentalSystem {
private RentalCar[] cars;
public CarRentalSystem(int size) {
cars = new RentalCar[size];
}
public void addCar(int index, RentalCar car) {
cars[index] = car;
}
public RentalCar getCar(int index) {
return cars[index];
}
public void rentCar(int index) {
cars[index].rent();
}
public void returnCar(int index) {
cars[index].returnCar();
}
public void displayCars() {
for (int i = 0; i < cars.length; i++) {
System.out.println(i + ": " + cars[i]);
}
}
public static void main(String[] args) {
CarRentalSystem system = new CarRentalSystem(3);
system.addCar(0, new RentalCar("Toyota", "Camry", 2020, 50.0));
system.addCar(1, new RentalCar("Honda", "Accord", 2021, 60.0));
system.addCar(2, new RentalCar("Nissan", "Altima", 2019, 40.0));
Scanner scanner = new Scanner(System.in);
int choice;
do {
System.out.println("1. Rent a car");
System.out.println("2. Return a car");
System.out.println("3. Display available cars");
System.out.println("4. Exit");
System.out.print("Enter your choice: ");
choice = scanner.nextInt();
switch (choice) {
case 1:
System.out.print("Enter car number to rent: ");
int rentIndex = scanner.nextInt();
system.rentCar(rentIndex);
break;
case 2:
System.out.print("Enter car number to return: ");
int returnIndex = scanner.nextInt();
system.returnCar(returnIndex);
break;
case 3:
system.displayCars();
break;
case 4:
System.out.println("Goodbye!");
break;
default:
System.out.println("Invalid choice, try again.");
break;
}
} while (choice != 4);
}
}
```
在CarRentalSystem类中,我们使用了一个RentalCar类型的数组来存储所有的租车,并添加了一些方法来管理这些租车。在main()方法中,我们创建了一些RentalCar对象,并添加到CarRentalSystem类中。然后,我们使用一个简单的菜单来让用户选择租车、还车或显示可用车辆。
阅读全文