如何用java语言来做一个进行选车的出租车的并进行计费案例!
参考:
import java.util.ArrayList;
import java.util.Scanner;
public class TaxiSystem {
private ArrayList<Taxi> taxis; // 所有出租车信息
private Taxi selectedTaxi; // 选中的出租车
private double mileage; // 行驶里程
private double fee; // 总费用
// 构造函数,初始化出租车信息
public TaxiSystem() {
this.taxis = new ArrayList<>();
this.taxis.add(new Taxi("京A12345", 10));
this.taxis.add(new Taxi("京B23456", 12));
this.taxis.add(new Taxi("京C34567", 15));
this.selectedTaxi = null;
this.mileage = 0.0;
this.fee = 0.0;
}
// 选择出租车
public void selectTaxi(String licensePlate) {
for (Taxi taxi : taxis) {
if (taxi.getLicensePlate().equals(licensePlate)) {
selectedTaxi = taxi;
System.out.println("您选择的出租车是:" + taxi.getLicensePlate());
break;
}
}
if (selectedTaxi == null) {
System.out.println("没有找到对应的出租车,请重新选择!");
}
}
// 行驶指定里程
public void drive(double mileage) {
if (selectedTaxi != null) {
double cost = selectedTaxi.calculateCost(mileage);
System.out.println("行驶了" + mileage + "公里,费用为:" + cost + "元。");
fee += cost;
this.mileage += mileage;
} else {
System.out.println("请先选择出租车!");
}
}
// 显示总里程和总费用
public void showSummary() {
System.out.println("总里程为:" + mileage + "公里,总费用为:" + fee + "元。");
}
public static void main(String[] args) {
TaxiSystem taxiSystem = new TaxiSystem();
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("请选择操作:1. 选择出租车;2. 行驶;3. 显示总里程和总费用;4. 退出");
int choice = scanner.nextInt();
switch (choice) {
case 1:
System.out.println("请输入出租车车牌号码:");
String licensePlate = scanner.next();
taxiSystem.selectTaxi(licensePlate);
break;
case 2:
System.out.println("请输入行驶里程:");
double mileage = scanner.nextDouble();
taxiSystem.drive(mileage);
break;
case 3:
taxiSystem.showSummary();
break;
case 4:
System.out.println("谢谢使用!");
return;
default:
System.out.println("无效操作,请重新选择!");
break;
}
}
}
}
class Taxi {
private String licensePlate; // 车牌号码
private double unitPrice; // 单价
public Taxi(String licensePlate, double unitPrice) {
this.licensePlate = licensePlate;
this.unitPrice = unitPrice;
}
public String getLicensePlate() {
return licensePlate;
}
public double calculateCost(double mileage) {
return unitPrice * mileage;
}
https://blog.csdn.net/weixin_45915263/article/details/114006315