继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

Java入门第二季实战——答答租车系统

慕圣0830664
关注TA
已关注
手记 3
粉丝 6
获赞 4
  • CargoCapacity.java
/**
 * 载货能力接口
 */
public interface CargoCapacity {
    // 获取载货量
    float getWeight();
}
  • MannedCapacity.java
/**
 * 载人能力接口
 */
public interface MannedCapacity {
    // 获取载人数
    int getNumber();
}
  • Car.java
/**
 * 车的基类,封装通用属性
 */
public class Car { //定义父类
    private int id; //编号
    private String name; //名字
    private float price; //价格

    //定义构造方法
    public Car(int id, String name, float price) {
        this.id = id;
        this.name = name;
        this.price = price;
    }

    public int getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public float getPrice() {
        return price;
    }
}
  • CargoCar.java
/**
 * 载货汽车
 */
public class CargoCar extends Car implements CargoCapacity {
    private float weight; // 载货量

    public CargoCar(int id, String name, float price, float weight) {
        super(id, name, price);
        this.weight = weight;
    }

    @Override
    public float getWeight() {
        return this.weight;
    }

    @Override
    public String toString() {
        return this.getId() + "\t" + this.getName() + "\t " + this.getPrice() + "元/天\t载货:" + getWeight() + "吨";
    }
}
  • MannedCar.java
/**
 * 载人汽车
 */
public class MannedCar extends Car implements MannedCapacity {
    private int number; // 载人数

    public MannedCar(int id, String name, float price, int number) {
        super(id, name, price);
        this.number = number;
    }

    @Override
    public int getNumber() {
        return this.number;
    }

    @Override
    public String toString() {
        return this.getId() + "\t" + this.getName() + "\t " + this.getPrice() + "元/天\t载人:" + this.getNumber() + "人";
    }
}

  • MannedCargoCar.java
/**
 * 可同时载人和载货的汽车
 */
public class MannedCargoCar extends Car implements MannedCapacity, CargoCapacity {

    private int number; // 裁人数
    private float weight; // 载货数

    public MannedCargoCar(int id, String name, float price, int number, float weight) {
        super(id, name, price);
        this.number = number;
        this.weight = weight;
    }

    @Override
    public int getNumber() {
        return this.number;
    }

    @Override
    public float getWeight() {
        return this.weight;
    }

    @Override
    public String toString() {
        return this.getId() + "\t" + this.getName() + "\t " + this.getPrice() + "元/天\t载人:" + getNumber() + "人\t载货:" + getWeight() + "吨";
    }

}
  • RentalItem.java
/**
 * 租赁项,每选择租赁一种车都对应一个RentalItem
 */
public class RentalItem {
    private Car car; // 租赁的汽车
    private Integer days; // 租赁天数
    private Integer quantity; // 租赁数量

    public RentalItem(Car car, Integer days, Integer quantity) {
        this.car = car;
        this.days = days;
        this.quantity = quantity;
    }

    public float getRent() {
        return this.car.getPrice() * this.days * this.quantity;
    }

    public int getNumber() {
        if (isMannedCar()) {
            return ((MannedCapacity) car).getNumber();
        }
        return 0;
    }

    public float getWeight() {
        if (isCargoCar()) {
            return ((CargoCapacity) car).getWeight();
        }
        return 0;
    }

    public boolean isMannedCar() {
        return car instanceof MannedCapacity;
    }

    public boolean isCargoCar() {
        return car instanceof CargoCapacity;
    }

    public String getName() {
        return car.getName();
    }
}
  • CarManager.java
import java.util.ArrayList;
import java.util.List;

/**
 * Car管理类
 */
public class CarManager {

    private List<Car> cars = new ArrayList<>();

    public CarManager() {
        init();
    }

    //初始化Car集合
    private void init() {
        add(new MannedCar(getCarId(), "奥迪A4", 500, 4));
        add(new MannedCar(getCarId(), "马自达6", 400, 4));
        add(new MannedCargoCar(getCarId(), "皮卡雪6", 450, 4, 2));
        add(new MannedCar(getCarId(), "金龙", 800, 20));
        add(new CargoCar(getCarId(), "松花江", 400, 4));
        add(new CargoCar(getCarId(), "依维柯", 1000, 20));
    }

    public void add(Car car) {
        cars.add(car);
    }

    //菜单显示
    public void showMenu() {
        System.out.println("========可租车的类型及其价目表========");
        System.out.println("序号\t" + "汽车名称   " + "租金\t\t  " + "容量");
        cars.forEach(System.out::println);
    }

    public Car get(int index) {
        return cars.get(index - 1);
    }

    public boolean hasIndex(Integer carId) {
        return carId > 0 && carId <= cars.size();
    }

    private int getCarId() {
        return cars.size() + 1;
    }
}
  • RentalBill.java
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 租赁清单
 */
public class RentalBill {

    private Map<Integer, RentalItem> itemMap = new HashMap<>();

    public void add(RentalItem item) {
        // 如果重复租赁相同的车辆,则叠加租赁天数和租赁数量
        if (itemMap.containsKey(item.getId())) {
            RentalItem existItem = itemMap.get(item.getId());
            existItem.setDays(existItem.getDays() + item.getDays());
            existItem.setQuantity(existItem.getQuantity() + item.getQuantity());
        } else {
            itemMap.put(item.getId(), item);
        }
    }

    public void showBill() {
        System.out.println("=============您的账单=============");
        System.out.println("***可载人的车有:" + "\n\t" + mannedCarNames() + " 共载人:" + totalNumber() + "人");
        System.out.println("***可载货的车有:" + "\n\t" + cargoCarNames() + " 共载货:" + totalWeight() + "吨");
        System.out.println("***租车总价格:" + totalRent() + "元");
    }

    private List<String> mannedCarNames() {
        return getCarNames(RentalItem::isMannedCar);
    }

    private List<String> cargoCarNames() {
        return getCarNames(RentalItem::isCargoCar);
    }

    private List<String> getCarNames(Function<RentalItem, Boolean> condition) {
        return itemMap.values().stream().filter(item -> condition.apply(item)).map(RentalItem::getName).collect(Collectors.toList());
    }

    private Integer totalNumber() {
        return itemMap.values().stream().filter(RentalItem::isMannedCar).map(RentalItem::getNumber).reduce(Integer::sum).get();
    }

    private Float totalWeight() {
        return itemMap.values().stream().filter(RentalItem::isCargoCar).map(RentalItem::getWeight).reduce(Float::sum).get();
    }

    private Float totalRent() {
        return itemMap.values().stream().map(RentalItem::getRent).reduce(0f, (sum, rent) -> sum += rent);
    }

}
  • CarRentalSystem.java
import java.util.Scanner;
import java.util.function.Function;

/**
 * 租车系统
 */
public class CarRentalSystem {
    private Scanner scanner = new Scanner(System.in);
    private RentalBill rentalBill = new RentalBill();
    private CarManager carManager = new CarManager();

    public void launch() {
        System.out.println("欢迎使用答答租车系统:");

        if (goOn()) {
            showMenu();
            collectRentalItems();
            showBill();
        } else {
            System.out.println("谢谢使用!客官慢走!");
        }
    }

    /**
     * 显示菜单
     */
    private void showMenu() {
        carManager.showMenu();
    }

    /**
     * 显示租赁清单
     */
    private void showBill() {
        rentalBill.showBill();
    }

    /**
     * 收集用户选择的租赁信息
     */
    private void collectRentalItems() {
        while (true) {
            // 获取车辆序号
            int carId = getInputCarId();
            Car car = carManager.get(carId);
            // 获取租赁数量
            int quantity = getInputQuantity(car.getName());
            // 获取租赁天数
            int days = getInputDays(car.getName());

            rentalBill.add(new RentalItem(car, days, quantity));

            System.out.print("是否选择继续租赁操作?(n:退出,并打印租赁清单;其他任意键继续):");
            String input = scanner.next();
            if ("N".equalsIgnoreCase(input.trim())) {
                break;
            }
        }
    }

    private boolean goOn() {
        int key = getInput("您是否要租车?(1是 0否):", input -&gt; {
            if (input != 0 &amp;&amp; input != 1) {
                System.out.println("请输入数字1或0!");
                return false;
            }
            return true;
        });
        return key == 1;
    }

    private int getInputDays(String name) {
        return getInput("请输入["+name+"]的租赁天数:", days -&gt; {
            if (days &lt; 1) {
                System.out.println("不合法的租赁天数,请重新输入!");
                return false;
            }
            return true;
        });
    }

    private int getInputQuantity(String name) {
        return getInput("请输入["+name+"]的租赁数量:", quantity -&gt; {
            if (quantity &lt; 1 ) {
                System.out.println("不合法的租赁数量,请重新输入!");
                return false;
            }
            return true;
        });
    }

    private int getInputCarId() {
        return getInput("请输入要租赁的车辆序号:", carId -&gt; {
            if (!carManager.hasIndex(carId)) {
                System.out.println("不合法的车辆序号,请重新输入!");
                return false;
            }
            return true;
        });
    }

    /**
     * 从控制台接受用户输入的一个正整数
     *
     * @param hint     提示信息
     * @param function 用户判断用户输入的信息是否合法,如果不合法,需要重新输入
     * @return
     */
    private int getInput(String hint, Function function) {
        while (true) {
            System.out.print(hint);
            try {
                int input = scanner.nextInt();
                if (!function.apply(input)) {
                    continue;
                }
                return input;
            } catch (Exception e) {
                System.out.println("输入不合法!请重新输入!");
                // 如果出现异常,则跳过本次输入的信息
                scanner = scanner.skip(".*");
            }
        }
    }
}
  • Test.java
/**
 * 启动类
 */
public class Test {
    public static void main(String[] args) {
        new CarRentalSystem().launch();
    }
}
打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP