草庐IT

[面向对象程序设计] 汽车租赁系统(Java实现)

离歌_lige 2023-08-25 原文

通过Java简单实现汽车租赁系统。

1)系统分为管理员和用户角色登录,不同的角色有不同的权限操作;

2)管理员功能:查看、添加、修改和删除车辆信息,查看营业额;

3)用户功能:登录后,可以查看车辆、租车、换车,模拟付款等;

查看车辆:查看可租/已租车辆;特定类型查看;

租车:租赁几天;

换车:更换车辆;

模拟付款:购物车模拟;

4)车辆:高级版(考虑三种车型Car,Bus, Trunk);

考虑三种车型Car,Bus, Trunk(继承于父类Vehicle)

5)存储:用文件或数据库进行数据存储。

目录结构一览

汽车类型包:存放三种不同的车型,每种车有一种独特属性

Vehicle父类

package com.school.experience.RentCarSystem.Cars;

public class Vehicle {//所有车型公共属性
    private String brand;
    private String type;
    private String carId;
    private double rentMoney;
    private boolean isRent = false;
    private int rentDays = 0;
    private String owner = "";
    private String kinds = "";

    public int getRentDays() {
        return rentDays;
    }

    public void setRentDays(int rentDays) {
        this.rentDays = rentDays;
    }

    public Vehicle(){}
    public Vehicle(String brand, String type, String carId, double rentMoney) {
        this.brand = brand;
        this.type = type;
        this.carId = carId;
        this.rentMoney = rentMoney;
    }

    public String getBrand() {
        return brand;
    }
    public String getType() {
        return type;
    }
    public String getCarId() {
        return carId;
    }
    public double getRentMoney() {
        return rentMoney;
    }

    public boolean getIsRent() {
        return isRent;
    }

    public String getOwner() {
        return owner;
    }

    public String getKinds() {
        return kinds;
    }

    public void setBrand(String brand) {
        this.brand = brand;
    }
    public void setType(String type) {
        this.type = type;
    }
    public void setCarId(String carId) {
        this.carId = carId;
    }
    public void setRentMoney(double rentMoney) {
        this.rentMoney = rentMoney;
    }

    public void setIsRent(boolean rent) {
        isRent = rent;
    }

    public void setOwner(String owner) {
        this.owner = owner;
    }

    public void setKinds(String kinds) {
        this.kinds = kinds;
    }

    @Override
    public String toString(){
        return "["+getBrand()+" "+getType()+" "+getCarId()+" "+getRentMoney()+"]";
    }
}

Bus子类

package com.school.experience.RentCarSystem.Cars;

public class Bus extends Vehicle{//巴士车型
    private int passengerCapacity;

    public Bus(String brand, String type, String carId, double rentMoney, int passengerCapacity) {
        super(brand, type, carId, rentMoney);
        this.passengerCapacity = passengerCapacity;
        this.setKinds("Bus");
    }

    public int getPassengerCapacity() {
        return passengerCapacity;
    }
    public void setPassengerCapacity(int passengerCapacity) {
        this.passengerCapacity = passengerCapacity;
    }

    @Override
    public String toString(){
        return "["+getBrand()+" "+getType()+" "+getCarId()+" "+"日租金:"+getRentMoney()
                +" "+"载客数:"+getPassengerCapacity()+"]";
    }
}

Car子类

package com.school.experience.RentCarSystem.Cars;

public class Car extends Vehicle{//轿车车型
    private int comfortLevel;

    public Car(String brand, String type, String carId, double rentMoney, int comfortLevel) {
        super(brand, type, carId, rentMoney);
        this.comfortLevel = comfortLevel;
        this.setKinds("Car");
    }

    public int getComfortLevel() {
        return comfortLevel;
    }
    public void setComfortLevel(int comfortLevel) {
        this.comfortLevel = comfortLevel;
    }

    @Override
    public String toString(){
        return "["+getBrand()+" "+getType()+" "+getCarId()+" "+"日租金:"+getRentMoney()
                +" "+"舒适度:"+getComfortLevel()+"]";
    }
}

Trunk子类

package com.school.experience.RentCarSystem.Cars;

public class Trunk extends Vehicle{//货车车型
    private double bearingCapacity;

    public Trunk(String brand, String type, String carId, double rentMoney, double bearingCapacity) {
        super(brand, type, carId, rentMoney);
        this.bearingCapacity = bearingCapacity;
        this.setKinds("Trunk");
    }

    public double getBearingCapacity() {
        return bearingCapacity;
    }
    public void setBearingCapacity(double bearingCapacity) {
        this.bearingCapacity = bearingCapacity;
    }

    @Override
    public String toString(){
        return "["+getBrand()+" "+getType()+" "+getCarId()+" "+"日租金:"+getRentMoney()
                +" " +"载货量:"+getBearingCapacity()+"]";
    }
}

 CatchException包:负责各种异常的处理及提示

Interface_Error接口
package com.school.experience.RentCarSystem.CatchException;

public interface Interface_Error {
    void printError();//告知错误原因
}
ErrorSetException类
package com.school.experience.RentCarSystem.CatchException;

public class ErrorSetException extends Exception implements Interface_Error{
    public void printError(){
        System.out.println("充值失败,充值金额不可为负数!");
    }
}

OverChoiceException类
package com.school.experience.RentCarSystem.CatchException;

public class OverChoiceException extends Exception implements Interface_Error{//选择超出范围,用于判断用户选择车型
    public void printError(){
        System.out.println("抱歉,您想要租赁的车型不存在!");
    }

    public void printErrorM(){
        System.out.println("抱歉,您想要添加的车型不存在!");
    }
}

DataBase包:用于存放数据信息,这里采用文件存储,有能力可以自行更换为数据库存储管理

Garage类:读写车辆信息

package com.school.experience.RentCarSystem.DataBase;

import com.school.experience.RentCarSystem.Cars.*;
import java.io.*;
import java.util.LinkedList;

public class Garage {//车库,存放待租赁车辆信息
    public LinkedList<Vehicle> CarSet;//待租车辆
    public LinkedList<Vehicle> RentSet;//已租车辆
    public Vehicle v;
    File file;
    public Garage() throws IOException {
        CarSet = new LinkedList<>();
        RentSet = new LinkedList<>();
        v = new Vehicle();
        String carPath = "E:\\Workspace\\IDEA_Java\\MianDuiObjectInSchool" +
                "\\src\\com\\school\\experience\\RentCarSystem\\DataBase\\carPath.txt";
        file = new File(carPath);
        ReadGarage();
    }
    //通过判断是否已经出租,来将车辆添加到不同的集合里
    //把车的属性分行存储,一个车占五行,先判断是否出租再添加到集合
    public void ReadGarage() throws IOException {
        BufferedReader br = new BufferedReader(new FileReader(file));
        String line;
        int i=1;
        String tem="";
        while ((line=br.readLine())!=null) {
            if(i%9==1){
                v.setBrand(line);//品牌
            }else if(i%9==2){
                v.setType(line);//型号
            } else if (i%9==3) {
                v.setCarId(line);//车牌号
            } else if (i%9==4) {
                v.setRentMoney(Double.parseDouble(line));//租金
            } else if (i%9==5) {
                tem = line;//特有量
            } else if (i%9==6) {
                v.setIsRent(Boolean.parseBoolean(line));//出租情况
            } else if (i%9==7) {
                v.setRentDays(Integer.parseInt(line));//租赁天数
            } else if (i%9==8) {
                v.setOwner(line);//所有人
            } else if (i%9==0) {
                v.setKinds(line);//车的种类
            }
            if(i%9==0){
                switch (v.getKinds()) {
                    case "Bus" -> {
                        Bus temBus = new Bus(v.getBrand(), v.getType()
                                , v.getCarId(), v.getRentMoney(), Integer.parseInt(tem));
                        temBus.setIsRent(v.getIsRent());
                        temBus.setRentDays(v.getRentDays());
                        temBus.setOwner(v.getOwner());
                        temBus.setKinds(v.getKinds());
                        if (!v.getIsRent()) {
                            CarSet.add(temBus);
                        } else {
                            RentSet.add(temBus);
                        }
                    }
                    case "Car" -> {
                        Car temCar = new Car(v.getBrand(), v.getType()
                                , v.getCarId(), v.getRentMoney(), Integer.parseInt(tem));
                        temCar.setIsRent(v.getIsRent());
                        temCar.setRentDays(v.getRentDays());
                        temCar.setOwner(v.getOwner());
                        temCar.setKinds(v.getKinds());
                        if (!v.getIsRent()) {
                            CarSet.add(temCar);
                        } else {
                            RentSet.add(temCar);
                        }
                    }
                    case "Trunk" -> {
                        Trunk temTrunk = new Trunk(v.getBrand(), v.getType()
                                , v.getCarId(), v.getRentMoney(), Double.parseDouble(tem));
                        temTrunk.setIsRent(v.getIsRent());
                        temTrunk.setRentDays(v.getRentDays());
                        temTrunk.setOwner(v.getOwner());
                        temTrunk.setKinds(v.getKinds());
                        if (!v.getIsRent()) {
                            CarSet.add(temTrunk);
                        } else {
                            RentSet.add(temTrunk);
                        }
                    }
                }
            }
            i++;
        }
        br.close();
    }
    //直接把所有车写到一起
    public void WriteGarage() throws IOException {
        BufferedWriter bw = new BufferedWriter(new FileWriter(file));
        for (Vehicle v:
                CarSet) {
            bw.write(v.getBrand());
            bw.newLine();
            bw.write(v.getType());
            bw.newLine();
            bw.write(v.getCarId());
            bw.newLine();
            bw.write(String.valueOf(v.getRentMoney()));
            bw.newLine();
            if(v instanceof Bus){
                bw.write(String.valueOf(((Bus) v).getPassengerCapacity()));
            } else if (v instanceof Car) {
                bw.write(String.valueOf(((Car) v).getComfortLevel()));
            } else if (v instanceof Trunk) {
                bw.write(String.valueOf(((Trunk) v).getBearingCapacity()));
            }
            bw.newLine();
            bw.write(String.valueOf(v.getIsRent()));
            bw.newLine();
            bw.write(String.valueOf(v.getRentDays()));
            bw.newLine();
            bw.write(v.getOwner());
            bw.newLine();
            bw.write(v.getKinds());
            bw.newLine();
        }
        for (Vehicle v:
                RentSet) {
            bw.write(v.getBrand());
            bw.newLine();
            bw.write(v.getType());
            bw.newLine();
            bw.write(v.getCarId());
            bw.newLine();
            bw.write(String.valueOf(v.getRentMoney()));
            bw.newLine();
            if(v instanceof Bus){
                bw.write(String.valueOf(((Bus) v).getPassengerCapacity()));
            } else if (v instanceof Car) {
                bw.write(String.valueOf(((Car) v).getComfortLevel()));
            } else if (v instanceof Trunk) {
                bw.write(String.valueOf(((Trunk) v).getBearingCapacity()));
            }
            bw.newLine();
            bw.write(String.valueOf(v.getIsRent()));
            bw.newLine();
            bw.write(String.valueOf(v.getRentDays()));
            bw.newLine();
            bw.write(v.getOwner());
            bw.newLine();
            bw.write(v.getKinds());
            bw.newLine();
        }
        bw.flush();
        bw.close();
    }
}

User类:用户类

package com.school.experience.RentCarSystem.DataBase;

public class User {
    private String account;
    private String password;
    private double money;
    private int type;//管理员是1,用户为0

    public User(){}
    public User(String account, String password, double money, int type) {
        this.account = account;
        this.password = password;
        this.money = money;
        this.type = type;
    }

    public String getAccount() {
        return account;
    }

    public void setAccount(String account) {
        this.account = account;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public double getMoney() {
        return money;
    }

    public void setMoney(double money) {
        this.money = money;
    }

    public int getType() {
        return type;
    }

    public void setType(int type) {
        this.type = type;
    }
}

UserData类:读写用户信息

package com.school.experience.RentCarSystem.DataBase;

import java.io.*;
import java.util.LinkedList;

public class UserData {
    public LinkedList<User> UserSet;

    public User u;
    File file;
    public UserData() throws IOException {
        UserSet = new LinkedList<>();
        u = new User();
        String userPath = "E:\\Workspace\\IDEA_Java\\MianDuiObjectInSchool" +
                "\\src\\com\\school\\experience\\RentCarSystem\\DataBase\\userPath.txt";
        file = new File(userPath);
        ReadUser();
    }
    //通过判断是否用户类型,来将用户赋予不同权限
    //把用户的属性分行存储,一个用户占四行,先判断用户类型再分配权限
    public void ReadUser() throws IOException {
        BufferedReader br = new BufferedReader(new FileReader(file));
        String line;
        int i=1;
        while ((line=br.readLine())!=null) {
            if(i%4==1){
                u.setAccount(line);//用户名
            }else if(i%4==2){
                u.setPassword(line);//密码
            } else if (i%4==3) {
                u.setMoney(Double.parseDouble(line));//钱包余额/营业额
            } else if (i%4==0) {
                u.setType(Integer.parseInt(line));//用户类型
            }
            User temUser;
            if(i%4==0){
                temUser = new User(u.getAccount(),u.getPassword(),u.getMoney(),u.getType());
                UserSet.add(temUser);
            }
            i++;
        }
        br.close();
    }
    //把所有用户写到一起
    public void WriteUser() throws IOException {
        BufferedWriter bw = new BufferedWriter(new FileWriter(file));
        for (User u:
                UserSet) {
            bw.write(u.getAccount());
            bw.newLine();
            bw.write(u.getPassword());
            bw.newLine();
            bw.write(String.valueOf(u.getMoney()));
            bw.newLine();
            bw.write(String.valueOf(u.getType()));
            bw.newLine();
        }
        bw.flush();
        bw.close();
    }
}

Login包

ToLogin类

package com.school.experience.RentCarSystem.Login;

import com.school.experience.RentCarSystem.DataBase.User;
import com.school.experience.RentCarSystem.Menu.MenuLogin;
import java.util.LinkedList;
import java.util.Scanner;

public class ToLogin {//登录功能
    private String account;
    private String password;

    public String getAccount() {
        return account;
    }
    public void setAccount(String account) {
        this.account = account;
    }

    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }

    public User toLog(LinkedList<User> UserSet){//登录尝试
        MenuLogin.logMenu();
        Scanner sc = new Scanner(System.in);
        System.out.print("账户:");
        setAccount(sc.next());
        System.out.print("密码:");
        setPassword(sc.next());
        User u;
        u = searchAccount(UserSet,account,password);
        return u;
    }

    public User searchAccount(LinkedList<User> UserSet,String account, String password){//检索用户
        boolean on = false;
        User user = new User();
        user.setType(2);
        //0代表用户。1代表管理员。2代表非法账户
        for (User u:
             UserSet) {
            if(u.getAccount().equals(account)&&u.getPassword().equals(password)&&u.getType()==0){
                System.out.println("尊敬的用户"+account+"欢迎登录。");
                on = true;
                user = u;
                break;
            } else if (u.getAccount().equals(account)&&u.getPassword().equals(password)&&u.getType()==1) {
                System.out.println("尊敬的管理员"+account+"欢迎登录。");
                on = true;
                user = u;
                break;
            }
        }
        if(!on){
            System.out.println("账号或者密码输入错误!请重试。");
        }
        return user;
    }
}

Menu包:封装了界面内容

MenuCustom类

package com.school.experience.RentCarSystem.Menu;

public class MenuCustom {//顾客界面
    public static void mainCustomMenu(){
        System.out.println("您好用户,请选择你想要使用的功能:");
        System.out.println("1.租车   2.查看车辆   3.换租   4.模拟付款   \n5.查看余额   6.查看已租   7.充值   8.还车   0.退出");
    }
    public static void seeCarMenu(){
        System.out.println("您好,目前可租赁的车辆如下表:");
    }
    public static void rentMenu(){
        System.out.println("您好,请问您想租赁什么车辆呢?我们有以下汽车种类:");
        System.out.println("1.轿车   2.客车   3.货车");
    }
    public static void yourRentMenu(){
        System.out.println("您好,您现在已经租用的车辆如下:");
    }

}

MenuLogin类

package com.school.experience.RentCarSystem.Menu;

public class MenuLogin {//登录界面
    public static void logMenu(){
        System.out.println("******_____欢迎使用秋朗汽车租赁系统_____******");
        System.out.println("请输入您的账户与密码:");
    }
}

MenuManager

package com.school.experience.RentCarSystem.Menu;

public class MenuManager {//管理员界面
    public static void mainManagerMenu(){
        System.out.println("您好管理员,请选择你想要使用的功能:");
        System.out.println("1.查看车辆   2.添加   3.修改   4.删除   \n5.查看营业额   6.查看租车记录   7.查看用户   0.退出");
    }
    public static void seeCarMenu1(){
        System.out.println("您好,目前待出售的车辆如下表:");
    }
    public static void seeCarMenu2(){
        System.out.println("您好,目前已出售的车辆如下表:");
    }
    public static void addMenu(){
        System.out.println("您好,请问您想添加什么车辆呢?我们有以下汽车种类:");
        System.out.println("1.轿车   2.客车   3.货车");
    }
    public static void exchangeMenu(){
        System.out.println("请输入您想要修改的车辆ID:");
    }
    public static void deleteMenu(){
        System.out.println("您好,请问您想删除什么车辆呢?我们有以下汽车种类:");
        System.out.println("1.轿车   2.客车   3.货车");
    }
}

Operation包:负责业务操作

前置业务接口

Interface_OFC接口
package com.school.experience.RentCarSystem.Operation;

import com.school.experience.RentCarSystem.Cars.Vehicle;
import com.school.experience.RentCarSystem.DataBase.*;
import java.io.IOException;
import java.util.LinkedList;

public interface Interface_OFC {
    void rentCar(Garage garage, User user, OperationForManager ofm) throws IOException;
    void seeCar(LinkedList<Vehicle> CarSet);
    void changeCar(LinkedList<Vehicle> CarSet,LinkedList<Vehicle> RentSet,
                   User user,OperationForManager ofm)throws IOException;
    void simulatePayments(LinkedList<Vehicle> CarSet);
    void checkRemaining(User user);
    void checkMyRent(LinkedList<Vehicle> RentSet,User user);
    void chargeMoney(User user);
    void returnCar(Garage garage, User user, OperationForManager ofm) throws IOException;
}
Interface_OFM接口
package com.school.experience.RentCarSystem.Operation;

import com.school.experience.RentCarSystem.Cars.Vehicle;
import com.school.experience.RentCarSystem.DataBase.*;
import java.io.IOException;
import java.util.LinkedList;

public interface Interface_OFM {
    void seeCar(Garage garage);
    void toAddCar(LinkedList<Vehicle> CarSet,LinkedList<Vehicle> RentSet);
    void exchangeCar(LinkedList<Vehicle> CarSet);
    void deleteCar(LinkedList<Vehicle> CarSet);
    void seeTurnover();
    void seeRentHistory() throws IOException;
    void showUser(LinkedList<User> UserSet);
}
OperationForCustom类
package com.school.experience.RentCarSystem.Operation;

import com.school.experience.RentCarSystem.Cars.*;
import com.school.experience.RentCarSystem.CatchException.*;
import com.school.experience.RentCarSystem.DataBase.*;
import com.school.experience.RentCarSystem.Menu.*;
import java.io.IOException;
import java.util.Scanner;
import java.util.LinkedList;

public class OperationForCustom implements Interface_OFC{//顾客功能,本身不存储数据
    public void rentCar(Garage garage, User user, OperationForManager ofm) throws IOException {//用户租赁汽车
        MenuCustom.rentMenu();
        Scanner in = new Scanner(System.in);
        int choice = in.nextInt();
        boolean no = true;
        try {
            if((choice!=1)&&(choice!=2)&&(choice!=3)){
                throw new OverChoiceException();
            }
        }catch (OverChoiceException e){
            e.printError();
            return;
        }
        if(choice==1){
            int i=1;
            for (Vehicle v:
                    garage.CarSet) {
                if(v instanceof Car){
                    System.out.println(i+". "+v.toString());
                    i++;
                }
            }
            System.out.println("请输入您想要的轿车的车牌号");
            String wantId = in.next();
            for (Vehicle v:
                    garage.CarSet) {
                if(v.getCarId().equals(wantId)){
                    System.out.println("请问你想要租几天呢?");
                    int days;
                    boolean rightDay=false;//保证租赁天数正确性
                    do {
                        days = in.nextInt();
                        if(days>0){
                            rightDay = true;
                        }else {
                            System.out.println("抱歉,租赁天数不可以为0或者负数!");
                        }
                    }
                    while(!rightDay);
                    double toPay = OperationForCustom.ComputeMoney(v,days);
                    System.out.println("您需要支付的租金为"+toPay);
                    if(toPay>user.getMoney()){
                        System.out.println("对不起您的余额不足,无法租赁。");
                        return;
                    }
                    System.out.println("感谢惠顾!");
                    String rentHistory=""+v.toString()+" 购买用户:"+user.getAccount()+" 租金:"+toPay+" 租赁天数:"+days;
                    ofm.writeRentHistory(rentHistory);//写入租赁记录
                    user.setMoney(user.getMoney()-toPay);//扣除余额
                    ofm.setTurnover(ofm.getTurnover()+toPay);//增加营业额
                    v.setIsRent(true);
                    v.setRentDays(days);
                    v.setOwner(user.getAccount());
                    garage.RentSet.add(v);
                    garage.CarSet.remove(v);
                    no = false;
                    break;
                }
            }
        } else if (choice==2) {
            int i=1;
            for (Vehicle v:
                    garage.CarSet) {
                if(v instanceof Bus){
                    System.out.println(i+". "+v.toString());
                    i++;
                }
            }
            System.out.println("请输入您想要的巴士的车牌号");
            String wantId = in.next();
            for (Vehicle v:
                    garage.CarSet) {
                if(v.getCarId().equals(wantId)){
                    System.out.println("请问你想要租几天呢?");
                    int days = in.nextInt();
                    double toPay = OperationForCustom.ComputeMoney(v,days);
                    System.out.println("您需要支付的租金为"+toPay);
                    if(toPay>user.getMoney()){
                        System.out.println("对不起您的余额不足,无法租赁。");
                        return;
                    }
                    System.out.println("感谢惠顾!");
                    String rentHistory=""+v.toString()+" 购买用户:"+user.getAccount()+" 租金:"+toPay+" 租赁天数:"+days;
                    ofm.writeRentHistory(rentHistory);
                    user.setMoney(user.getMoney()-toPay);
                    ofm.setTurnover(ofm.getTurnover()+toPay);
                    v.setIsRent(true);
                    v.setRentDays(days);
                    v.setOwner(user.getAccount());
                    garage.RentSet.add(v);
                    garage.CarSet.remove(v);
                    no = false;
                    break;
                }
            }
        } else {
            int i=1;
            for (Vehicle v:
                    garage.CarSet) {
                if(v instanceof Trunk){
                    System.out.println(i+". "+v.toString());
                    i++;
                }
            }
            System.out.println("请输入您想要的货车的车牌号");
            String wantId = in.next();
            for (Vehicle v:
                    garage.CarSet) {
                if(v.getCarId().equals(wantId)){
                    System.out.println("请问你想要租几天呢?");
                    int days = in.nextInt();
                    double toPay = OperationForCustom.ComputeMoney(v,days);
                    System.out.println("您需要支付的租金为"+toPay);
                    if(toPay>user.getMoney()){
                        System.out.println("对不起您的余额不足,无法租赁。");
                        return;
                    }
                    System.out.println("感谢惠顾!");
                    String rentHistory=""+v.toString()+" 购买用户:"+user.getAccount()+" 租金:"+toPay+" 租赁天数:"+days;
                    ofm.writeRentHistory(rentHistory);
                    user.setMoney(user.getMoney()-toPay);
                    ofm.setTurnover(ofm.getTurnover()+toPay);
                    v.setIsRent(true);
                    v.setRentDays(days);
                    v.setOwner(user.getAccount());
                    garage.RentSet.add(v);
                    garage.CarSet.remove(v);
                    no = false;
                    break;
                }
            }
        }
        if(no){
            System.out.println("找不到您想要的车辆!");
        }
    }
    public void rentCar(LinkedList<Vehicle> CarSet){//用户模拟租赁汽车
        MenuCustom.rentMenu();
        Scanner in = new Scanner(System.in);
        int choice = in.nextInt();
        boolean no = true;
        if(choice==1){
            int i=1;
            for (Vehicle v:
                    CarSet) {
                if(v instanceof Car){
                    System.out.println(i+". "+v.toString());
                    i++;
                }
            }
            System.out.println("请输入您想要的轿车的车牌号");
            String wantId = in.next();
            for (Vehicle v:
                    CarSet) {
                if(v.getCarId().equals(wantId)){
                    System.out.println("请问你想要租几天呢?");
                    System.out.println("本次模拟订单中,您需要支付的租金为"+ OperationForCustom.ComputeMoney(v,in.nextInt()));
                    System.out.println("感谢惠顾!");
                    CarSet.remove(v);
                    no = false;
                    break;
                }
            }
        } else if (choice==2) {
            int i=1;
            for (Vehicle v:
                    CarSet) {
                if(v instanceof Bus){
                    System.out.println(i+". "+v.toString());
                    i++;
                }
            }
            System.out.println("请输入您想要的巴士的车牌号");
            String wantId = in.next();
            for (Vehicle v:
                    CarSet) {
                if(v.getCarId().equals(wantId)){
                    System.out.println("请问你想要租几天呢?");
                    System.out.println("本次模拟订单中,您需要支付的租金为"+ OperationForCustom.ComputeMoney(v,in.nextInt()));
                    System.out.println("感谢惠顾!");
                    CarSet.remove(v);
                    no = false;
                    break;
                }
            }
        } else if (choice==3) {
            int i=1;
            for (Vehicle v:
                    CarSet) {
                if(v instanceof Trunk){
                    System.out.println(i+". "+v.toString());
                    i++;
                }
            }
            System.out.println("请输入您想要的货车的车牌号");
            String wantId = in.next();
            for (Vehicle v:
                    CarSet) {
                if(v.getCarId().equals(wantId)){
                    System.out.println("请问你想要租几天呢?");
                    System.out.println("本次模拟订单中,您需要支付的租金为"+ OperationForCustom.ComputeMoney(v,in.nextInt()));
                    System.out.println("感谢惠顾!");
                    CarSet.remove(v);
                    no = false;
                    break;
                }
            }
        }
        if(no){
            System.out.println("找不到您想要的车辆!");
        }
    }
    public static double ComputeMoney(Vehicle v,int day){//根据天数和车型计算租金
        if(day<=7){
            return v.getRentMoney()*day;
        } else if (day<=30) {
            System.out.println("恭喜您,本次租赁有9折优惠!");
            return v.getRentMoney()*day*0.9;
        } else if (day<=150) {
            System.out.println("恭喜您,本次租赁有8折优惠!");
            return v.getRentMoney()*day*0.8;
        } else  {
            System.out.println("恭喜您,本次租赁有7折优惠!");
            return v.getRentMoney()*day*0.7;
        }
    }
    public void seeCar(LinkedList<Vehicle> CarSet){//用户查看可租赁车辆的信息
        MenuCustom.seeCarMenu();
        int i=1;
        for (Vehicle v:
             CarSet) {
            Class<? extends Vehicle> look = v.getClass();
            String carKind="";
            if(look.getName().equals("com.school.experience.RentCarSystem.Cars.Bus")){
                carKind="客车";
            } else if (look.getName().equals("com.school.experience.RentCarSystem.Cars.Car")) {
                carKind="轿车";
            } else if (look.getName().equals("com.school.experience.RentCarSystem.Cars.Trunk")){
                carKind="货车";
            }
            System.out.println(i+". "+v.toString()+" 种类:"+carKind);
            i++;
        }
    }

    public void changeCar(LinkedList<Vehicle> CarSet,LinkedList<Vehicle> RentSet,
                          User user,OperationForManager ofm) throws IOException {//用户换租
        MenuCustom.yourRentMenu();
        int i=1;
        for (Vehicle v:
             RentSet) {
            if(v.getOwner().equals(user.getAccount())){
                System.out.println(i+". "+v.toString());
                i++;
            }
        }
        System.out.println("请输入您想要换租的车辆的车牌号:");
        Scanner in = new Scanner(System.in);
        String ex = in.next();
        boolean no = true;
        Vehicle out = null;
        for (Vehicle v:
                RentSet) {
            if(v.getCarId().equals(ex)){
                no = false;
                out = v;
                break;
            }
        }
        if(no){
            System.out.println("您想要换租的车辆不存在。");
            return;
        }

        no = true;
        System.out.println("目前可换租车辆如下");
        i=1;
        for (Vehicle v:
                CarSet) {
            System.out.println(i+". "+v.toString());
            i++;
        }
        System.out.println("请输出您想要的更换后的车辆的车牌号:");
        ex = in.next();
        for (Vehicle v:
                CarSet) {
            if(v.getCarId().equals(ex)){
                System.out.print("请输入更换车辆的租赁天数:");
                Scanner sc = new Scanner(System.in);
                int days = sc.nextInt();
                double difference = ComputeMoney(out,out.getRentDays())-ComputeMoney(v,days);//换购租金差值
                if(difference<0){//换租的车辆费用更高
                    if(user.getMoney()+difference<0){//账户余额无法支付差值
                        System.out.println("余额不足不可换租!");
                        return;
                    }else if(user.getMoney()+difference>0){//账户余额来填补差值
                        user.setMoney(user.getMoney()+difference);
                        System.out.println("余额已扣除换车租金差值"+Math.abs(difference));
                    }
                } else if (difference>0) {
                    user.setMoney(user.getMoney()+difference);
                    System.out.println("余额补偿换车租金差值"+Math.abs(difference));
                }
                String rentHistory=""+v.toString()+" 换购用户:"+user.getAccount()+" 差金:"+difference+" 租赁天数:"+days;
                ofm.writeRentHistory(rentHistory);//写入换购记录
                v.setIsRent(true);
                v.setRentDays(days);
                v.setOwner(out.getOwner());
                RentSet.add(v);
                CarSet.remove(v);

                out.setIsRent(false);
                out.setRentDays(0);
                out.setOwner("");
                CarSet.add(out);
                RentSet.remove(out);
                no = false;
                System.out.println("恭喜您,换租成功!");
                break;
            }
        }
        if(no){
            System.out.println("您想要更换的车辆不存在。");
        }
    }

    public void simulatePayments(LinkedList<Vehicle> CarSet){//用户模拟付款
        LinkedList<Vehicle> mod = new LinkedList<>(CarSet);
        rentCar(mod);
    }

    public void checkRemaining(User user){//获取用户的余额
        System.out.println("目前您的余额是"+user.getMoney());
    }

    public void checkMyRent(LinkedList<Vehicle> RentSet,User user){
        MenuCustom.yourRentMenu();
        int i=1;
        for (Vehicle v:
                RentSet) {
            if(v.getOwner().equals(user.getAccount())){
                System.out.println(i+". "+v.toString()+"租赁了"+v.getRentDays()+"天");
            }
            i++;
        }
    }
    public void chargeMoney(User user) {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入您想充值的金额:");
        try {
            double charge = sc.nextDouble();
            if(charge<0){
                throw new ErrorSetException();
            }
            user.setMoney(user.getMoney()+charge);
        }catch (ErrorSetException e){
            e.printError();
            return;
        }
        System.out.println("充值成功!");
    }
    public void returnCar(Garage garage, User user, OperationForManager ofm) throws IOException {
        checkMyRent(garage.RentSet,user);
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入您想归还的车辆的车牌号:");
        String outId = sc.next();
        boolean no = true;
        for (Vehicle v:
                garage.RentSet) {
            if (v.getCarId().equals(outId)) {
                String rentHistory=""+v.toString()+" 已归还,归还用户:"+user.getAccount();
                ofm.writeRentHistory(rentHistory);//写入归还记录
                System.out.println("归还成功!");
                v.setIsRent(false);
                v.setRentDays(0);
                v.setOwner("");
                garage.CarSet.add(v);
                garage.RentSet.remove(v);
                no = false;
                break;
            }
        }
        if(no){
            System.out.println("未找到可以归还的车辆。");
        }
    }
}
OperationForManager类
package com.school.experience.RentCarSystem.Operation;

import com.school.experience.RentCarSystem.Cars.*;
import com.school.experience.RentCarSystem.CatchException.OverChoiceException;
import com.school.experience.RentCarSystem.DataBase.*;
import com.school.experience.RentCarSystem.Menu.*;
import java.io.*;
import java.util.LinkedList;
import java.util.Scanner;

public class OperationForManager implements Interface_OFM{//管理员功能,本身不存储数据
    private double turnover;//实现不同的管理员看到的营业额同步
    File file;
    File fileH;

    public OperationForManager() throws IOException {
        String turnoverPath = "E:\\Workspace\\IDEA_Java\\MianDuiObjectInSchool" +
                "\\src\\com\\school\\experience\\RentCarSystem\\DataBase\\theTurnOver.txt";
        file = new File(turnoverPath);
        ReadTurnover();
        String rentHistory = "E:\\Workspace\\IDEA_Java\\MianDuiObjectInSchool" +
                "\\src\\com\\school\\experience\\RentCarSystem\\DataBase\\rentHistoryPath.txt";
        fileH = new File(rentHistory);
    }
    public double getTurnover() {
        return turnover;
    }

    public void setTurnover(double turnover) {
        this.turnover = turnover;
    }
    public void seeCar(Garage garage){//管理员查看所有车辆信息,包括已租和待租
        MenuManager.seeCarMenu1();
        int i=1;
        for (Vehicle v:
                garage.CarSet) {
            System.out.println(i+". "+v.toString());
            i++;
        }
        MenuManager.seeCarMenu2();
        i=1;
        for (Vehicle v:
                garage.RentSet) {
            System.out.println(i+". "+v.toString()+"(租赁顾客:"+v.getOwner()+" 租赁天数:"+v.getRentDays()+")");
            i++;
        }
    }
    public static void seeCar(LinkedList<Vehicle> CarSet){//管理员查看车辆信息,查看已租的
        MenuManager.seeCarMenu1();
        int i=1;
        for (Vehicle v:
                CarSet) {
            System.out.println(i+". "+v.toString());
            i++;
        }
    }

    @Deprecated
    public void toAddCar(LinkedList<Vehicle> CarSet,Vehicle v){CarSet.add(v);}
    public void toAddCar(LinkedList<Vehicle> CarSet,LinkedList<Vehicle> RentSet){//管理员添加车辆
        MenuManager.addMenu();
        Scanner in = new Scanner(System.in);
        int choice = in.nextInt();
        try {
            if((choice!=1)&&(choice!=2)&&(choice!=3)){
                throw new OverChoiceException();
            }
        }catch (OverChoiceException e){
            e.printErrorM();
            return;
        }
        if(choice==1){
            Car c;
            System.out.println("请依次输入您想要添加的轿车的品牌、型号、车牌号、日租金和舒适度:");
            try {
                c = new Car(in.next(), in.next(), in.next(), in.nextDouble(), in.nextInt());
            }catch (Exception e){
                e.getStackTrace();
                System.out.println("抱歉,输入格式不正确,无法添加车辆。");
                return;
            }
            boolean repeat=false;
            for (Vehicle v:
                    CarSet) {
                if(v.getCarId().equals(c.getCarId())){
                    repeat=true;
                }
            }
            for (Vehicle v:
                    RentSet) {
                if(v.getCarId().equals(c.getCarId())){
                    repeat=true;
                }
            }
            if(repeat){
                System.out.println("抱歉,新添车辆的车牌号与已知车辆冲突!");
                return;
            }
            System.out.println("添加成功,新的车辆已成功入库!");
            CarSet.add(c);
        } else if (choice==2) {
            Bus b;
            System.out.println("请依次输入您想要添加的客车的品牌、型号、车牌号、日租金和载客数:");
            try {
                b = new Bus(in.next(), in.next(), in.next(), in.nextDouble(), in.nextInt());
            }catch (Exception e){
                e.getStackTrace();
                System.out.println("抱歉,输入格式不正确,无法添加车辆。");
                return;
            }
            boolean repeat=false;//保证不会重复添加相同车牌号的车
            for (Vehicle v:
                    CarSet) {
                if(v.getCarId().equals(b.getCarId())){
                    repeat=true;
                }
            }
            for (Vehicle v:
                    RentSet) {
                if(v.getCarId().equals(b.getCarId())){
                    repeat=true;
                }
            }
            if(repeat){
                System.out.println("抱歉,新添车辆的车牌号与已知车辆冲突!");
                return;
            }
            System.out.println("添加成功,新的车辆已成功入库!");
            CarSet.add(b);
        } else {
            Trunk t;
            System.out.println("请依次输入您想要添加的货车的品牌、型号、车牌号、日租金和载货量:");
            try {
                t = new Trunk(in.next(), in.next(), in.next(), in.nextDouble(), in.nextDouble());
            }catch (Exception e){
                e.getStackTrace();
                System.out.println("抱歉,输入格式不正确,无法添加车辆。");
                return;
            }
            boolean repeat=false;
            for (Vehicle v:
                 CarSet) {
                if(v.getCarId().equals(t.getCarId())){
                    repeat=true;
                }
            }
            for (Vehicle v:
                 RentSet) {
                if(v.getCarId().equals(t.getCarId())){
                    repeat=true;
                }
            }
            if(repeat){
                System.out.println("抱歉,新添车辆的车牌号与已知车辆冲突!");
                return;
            }
            System.out.println("添加成功,新的车辆已成功入库!");
            CarSet.add(t);
        }
    }

    public void exchangeCar(LinkedList<Vehicle> CarSet){//管理员修改车辆信息
        OperationForManager.seeCar(CarSet);
        MenuManager.exchangeMenu();
        Scanner in = new Scanner(System.in);
        String ex = in.next();
        boolean no = true;
        for (Vehicle v:
                CarSet) {
            if(v.getCarId().equals(ex)){
                if(v instanceof Car){
                    System.out.println("请问您想修改什么信息(品牌,型号,车牌号,日租金,舒适度)");
                } else if (v instanceof Bus) {
                    System.out.println("请问您想修改什么信息(品牌,型号,车牌号,日租金,载客数)");
                } else if (v instanceof Trunk) {
                    System.out.println("请问您想修改什么信息(品牌,型号,车牌号,日租金,载货量)");
                }
                String info = in.next();
                exchangeCarInfo(v,info);
                System.out.println("车辆信息修改成功。");
                no = false;
                break;
            }
        }
        if(no){
            System.out.println("您想要修改的车辆不存在。");
        }
    }
    public void exchangeCarInfo(Vehicle v,String info){//修改车辆信息操作
        Scanner sc = new Scanner(System.in);
        switch (info) {
            case "品牌" -> {
                System.out.println("输入新的品牌");
                v.setBrand(sc.next());
            }
            case "型号" -> {
                System.out.println("输入新的型号");
                v.setType(sc.next());
            }
            case "车牌号" -> {
                System.out.println("输入新的车牌号");
                v.setCarId(sc.next());
            }
            case "日租金" -> {
                System.out.println("输入新的日租金");
                v.setRentMoney(sc.nextDouble());
            }
            case "舒适度" -> {
                System.out.println("输入新的舒适度");
                ((Car) v).setComfortLevel(sc.nextInt());
            }
            case "载客数" -> {
                System.out.println("输入新的载客数");
                ((Bus) v).setPassengerCapacity(sc.nextInt());
            }
            case "载货量" -> {
                System.out.println("输入新的载货量");
                ((Trunk) v).setBearingCapacity(sc.nextDouble());
            }
            default -> System.out.println("输入有误,本次不修改信息。");
        }
    }
    public void deleteCar(LinkedList<Vehicle> CarSet){//管理员删除汽车
        MenuManager.deleteMenu();
        Scanner in = new Scanner(System.in);
        int choice = in.nextInt();
        boolean no = true;
        if(choice==1){
            int i=1;
            for (Vehicle v:
                    CarSet) {
                if(v instanceof Car){
                    System.out.println(i+". "+v.toString());
                    i++;
                }
            }
            System.out.println("请输入您想要删除的轿车的车牌号");
            String wantId = in.next();
            for (Vehicle v:
                    CarSet) {
                if(v.getCarId().equals(wantId)){
                    CarSet.remove(v);
                    System.out.println("车辆"+wantId+"已删除");
                    no = false;
                    break;
                }
            }
        } else if (choice==2) {
            int i=1;
            for (Vehicle v:
                    CarSet) {
                if(v instanceof Bus){
                    System.out.println(i+". "+v.toString());
                    i++;
                }
            }
            System.out.println("请输入您想要删除的巴士的车牌号");
            String wantId = in.next();
            for (Vehicle v:
                    CarSet) {
                if(v.getCarId().equals(wantId)){
                    CarSet.remove(v);
                    System.out.println("车辆"+wantId+"已删除");
                    no = false;
                    break;
                }
            }
        } else if (choice==3) {
            int i=1;
            for (Vehicle v:
                    CarSet) {
                if(v instanceof Trunk){
                    System.out.println(i+". "+v.toString());
                    i++;
                }
            }
            System.out.println("请输入您想要删除的货车的车牌号");
            String wantId = in.next();
            for (Vehicle v:
                    CarSet) {
                if(v.getCarId().equals(wantId)){
                    CarSet.remove(v);
                    System.out.println("车辆"+wantId+"已删除");
                    no = false;
                    break;
                }
            }
        }
        if(no){
            System.out.println("您想要修改的车辆不存在。");
        }
    }

    public void seeTurnover(){//查看营业额
        System.out.println("目前营业额是"+getTurnover());
    }

    public void ReadTurnover() throws IOException {
        BufferedReader br = new BufferedReader(new FileReader(file));
        String line = br.readLine();
        setTurnover(Double.parseDouble(line));
        br.close();
    }

    public void WriteTurnover() throws IOException {
        BufferedWriter bw = new BufferedWriter(new FileWriter(file));
        bw.write(String.valueOf(getTurnover()));
        bw.flush();
        bw.close();
    }

    public void seeRentHistory() throws IOException {//查看租赁记录
        System.out.println("历史租车服务记录如下:");
        System.out.println(readRentHistory());
    }
    public String readRentHistory() throws IOException {//读取租赁记录
        BufferedReader br = new BufferedReader(new FileReader(fileH));
        StringBuilder history= new StringBuilder();
        String line;
        while ((line=br.readLine())!=null){
            history.append(line);
            history.append("\n");
        }
        br.close();
        return history.toString();
    }

    public void writeRentHistory(String history) throws IOException {//写入租赁记录
        BufferedWriter bw = new BufferedWriter(new FileWriter(fileH,true));
        bw.write(history);
        bw.newLine();
        bw.flush();
        bw.close();
    }

    public void showUser(LinkedList<User> UserSet){//展示用户
        System.out.println("目前所有用户如下:");
        int i=1;
        for (User u:
                UserSet) {
            System.out.print(i+". 账户名称:"+u.getAccount()+"  账户密码:"+u.getPassword());
            if(u.getType()==0){
                System.out.println("  管理权限:普通用户");
            } else if (u.getType()==1) {
                System.out.println("  管理权限:管理员");
            }
        }
    }
}

Rent包:封装运行过程

RentCarSys类
package com.school.experience.RentCarSystem.Rent;

import com.school.experience.RentCarSystem.DataBase.*;
import com.school.experience.RentCarSystem.Login.ToLogin;
import com.school.experience.RentCarSystem.Menu.*;
import com.school.experience.RentCarSystem.Operation.*;
import java.io.IOException;
import java.util.Scanner;
import java.util.concurrent.TimeUnit;

public class RentCarSys {
    public void starRentCarSys() throws IOException {
        boolean hadLog = false;//检测是否合法登录

        while (!hadLog){//登录
            //每一次登录都会刷新读取数据信息
            Garage garage = new Garage();//自动检索车辆信息
            UserData userData= new UserData();//自动检索用户信息
            OperationForManager ofm = new OperationForManager();//管理员操作实例化,自动获取营业额
            OperationForCustom ofc = new OperationForCustom();//用户操作实例化

            Scanner sc = new Scanner(System.in);
            ToLogin toLogin = new ToLogin();//登录操作实例化

            boolean out = false;//检测用户登录/登出

            User thisUser;//通过thisUser,检测登录用户类型,获取用户属性

            thisUser = toLogin.toLog(userData.UserSet);
            if(thisUser.getType()==0||thisUser.getType()==1){//检测是否合法账户
                hadLog = true;
                switch (thisUser.getType()){//不同用户功能界面不同
                    case 0:
                        while (!out){//测试顾客功能
                            MenuCustom.mainCustomMenu();
                            switch (sc.nextInt()) {
                                case 1 -> ofc.rentCar(garage, thisUser, ofm);//租车
                                case 2 -> ofc.seeCar(garage.CarSet);//查看可租赁汽车
                                case 3 -> ofc.changeCar(garage.CarSet, garage.RentSet, thisUser,ofm);//换租
                                case 4 -> ofc.simulatePayments(garage.CarSet);//模拟租车
                                case 5 -> ofc.checkRemaining(thisUser);//查看余额
                                case 6 -> ofc.checkMyRent(garage.RentSet,thisUser);//查看已租
                                case 7 -> ofc.chargeMoney(thisUser);//余额充值
                                case 8 -> ofc.returnCar(garage,thisUser,ofm);//归还车辆
                                case 0 -> {
                                    out = true;
                                    hadLog = false;
                                    garage.WriteGarage();//退出保存车辆信息
                                    ofm.WriteTurnover();//同步营业额
                                    userData.WriteUser();//保存刷新客户余额
                                }
                                default -> System.out.println("请输入合适的功能选项。");
                            }
                        }
                        break;
                    case 1:
                        while (!out){//测试管理员功能
                            MenuManager.mainManagerMenu();
                            switch (sc.nextInt()) {
                                case 1 -> ofm.seeCar(garage);//查看车辆
                                case 2 -> ofm.toAddCar(garage.CarSet,garage.RentSet);//添加车辆
                                case 3 -> ofm.exchangeCar(garage.CarSet);//修改车辆
                                case 4 -> ofm.deleteCar(garage.CarSet);//删除车辆
                                case 5 -> ofm.seeTurnover();//查看营业额
                                case 6 -> ofm.seeRentHistory();//查看租车记录
                                case 7 -> ofm.showUser(userData.UserSet);//查看用户
                                case 0 -> {
                                    out = true;
                                    hadLog = false;
                                    garage.WriteGarage();//退出保存车辆信息
                                }
                                default -> System.out.println("请输入合适的功能选项。");
                            }
                        }
                        break;
                }
            }else {
                System.out.println("是否继续登录?");
                String ch = sc.next();
                if(ch.equals("是")||ch.equals("yes")||ch.equals("Yes")||ch.equals("Y")||ch.equals("y")){
                    System.out.println("返回登录界面。。。");
                }else {
                    System.out.println("退出程序中......");
                    try {
                        TimeUnit.SECONDS.sleep(1);
                    }catch (InterruptedException e){
                        System.out.println("退出异常!");
                    }
                    System.out.println("退出成功。");
                    System.exit(0);
                }
            }

        }
    }

}

 最后添加一个TestSys类运行程序

package com.school.experience.RentCarSystem;

import com.school.experience.RentCarSystem.CatchException.*;
import com.school.experience.RentCarSystem.Rent.RentCarSys;
import java.io.IOException;

public class TestSys {//主界面
    public static void main(String[] args) throws IOException, OverChoiceException, ErrorSetException {
        RentCarSys s = new RentCarSys();
        s.starRentCarSys();
    }
}

 附上车的格式和用户格式

未租                                                已租

                                 

 

 

 

有关[面向对象程序设计] 汽车租赁系统(Java实现)的更多相关文章

  1. ruby - 如何从 ruby​​ 中的字符串运行任意对象方法? - 2

    总的来说,我对ruby​​还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用

  2. ruby - 在 Ruby 程序执行时阻止 Windows 7 PC 进入休眠状态 - 2

    我需要在客户计算机上运行Ruby应用程序。通常需要几天才能完成(复制大备份文件)。问题是如果启用sleep,它会中断应用程序。否则,计算机将持续运行数周,直到我下次访问为止。有什么方法可以防止执行期间休眠并让Windows在执行后休眠吗?欢迎任何疯狂的想法;-) 最佳答案 Here建议使用SetThreadExecutionStateWinAPI函数,使应用程序能够通知系统它正在使用中,从而防止系统在应用程序运行时进入休眠状态或关闭显示。像这样的东西:require'Win32API'ES_AWAYMODE_REQUIRED=0x0

  3. ruby-on-rails - Rails - 子类化模型的设计模式是什么? - 2

    我有一个模型:classItem项目有一个属性“商店”基于存储的值,我希望Item对象对特定方法具有不同的行为。Rails中是否有针对此的通用设计模式?如果方法中没有大的if-else语句,这是如何干净利落地完成的? 最佳答案 通常通过Single-TableInheritance. 关于ruby-on-rails-Rails-子类化模型的设计模式是什么?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.co

  4. ruby-on-rails - 按天对 Mongoid 对象进行分组 - 2

    在控制台中反复尝试之后,我想到了这种方法,可以按发生日期对类似activerecord的(Mongoid)对象进行分组。我不确定这是完成此任务的最佳方法,但它确实有效。有没有人有更好的建议,或者这是一个很好的方法?#eventsisanarrayofactiverecord-likeobjectsthatincludeatimeattributeevents.map{|event|#converteventsarrayintoanarrayofhasheswiththedayofthemonthandtheevent{:number=>event.time.day,:event=>ev

  5. ruby - 如何指定 Rack 处理程序 - 2

    Rackup通过Rack的默认处理程序成功运行任何Rack应用程序。例如:classRackAppdefcall(environment)['200',{'Content-Type'=>'text/html'},["Helloworld"]]endendrunRackApp.new但是当最后一行更改为使用Rack的内置CGI处理程序时,rackup给出“NoMethodErrorat/undefinedmethod`call'fornil:NilClass”:Rack::Handler::CGI.runRackApp.newRack的其他内置处理程序也提出了同样的反对意见。例如Rack

  6. ruby - 在 Ruby 中编写命令行实用程序 - 2

    我想用ruby​​编写一个小的命令行实用程序并将其作为gem分发。我知道安装后,Guard、Sass和Thor等某些gem可以从命令行自行运行。为了让gem像二进制文件一样可用,我需要在我的gemspec中指定什么。 最佳答案 Gem::Specification.newdo|s|...s.executable='name_of_executable'...endhttp://docs.rubygems.org/read/chapter/20 关于ruby-在Ruby中编写命令行实用程序

  7. ruby-on-rails - Rails 应用程序之间的通信 - 2

    我构建了两个需要相互通信和发送文件的Rails应用程序。例如,一个Rails应用程序会发送请求以查看其他应用程序数据库中的表。然后另一个应用程序将呈现该表的json并将其发回。我还希望一个应用程序将存储在其公共(public)目录中的文本文件发送到另一个应用程序的公共(public)目录。我从来没有做过这样的事情,所以我什至不知道从哪里开始。任何帮助,将不胜感激。谢谢! 最佳答案 无论Rails是什么,几乎所有Web应用程序都有您的要求,大多数现代Web应用程序都需要相互通信。但是有一个小小的理解需要你坚持下去,网站不应直接访问彼此

  8. ruby - 无法运行 Rails 2.x 应用程序 - 2

    我尝试运行2.x应用程序。我使用rvm并为此应用程序设置其他版本的ruby​​:$rvmuseree-1.8.7-head我尝试运行服务器,然后出现很多错误:$script/serverNOTE:Gem.source_indexisdeprecated,useSpecification.Itwillberemovedonorafter2011-11-01.Gem.source_indexcalledfrom/Users/serg/rails_projects_terminal/work_proj/spohelp/config/../vendor/rails/railties/lib/r

  9. ruby-on-rails - Rails 应用程序中的 Rails : How are you using application_controller. rb 是新手吗? - 2

    刚入门rails,开始慢慢理解。有人可以解释或给我一些关于在application_controller中编码的好处或时间和原因的想法吗?有哪些用例。您如何为Rails应用程序使用应用程序Controller?我不想在那里放太多代码,因为据我了解,每个请求都会调用此Controller。这是真的? 最佳答案 ApplicationController实际上是您应用程序中的每个其他Controller都将从中继承的类(尽管这不是强制性的)。我同意不要用太多代码弄乱它并保持干净整洁的态度,尽管在某些情况下ApplicationContr

  10. ruby-on-rails - 如何验证非模型(甚至非对象)字段 - 2

    我有一个表单,其中有很多字段取自数组(而不是模型或对象)。我如何验证这些字段的存在?solve_problem_pathdo|f|%>... 最佳答案 创建一个简单的类来包装请求参数并使用ActiveModel::Validations。#definedsomewhere,atthesimplest:require'ostruct'classSolvetrue#youcouldevencheckthesolutionwithavalidatorvalidatedoerrors.add(:base,"WRONG!!!")unlesss

随机推荐