Java-简单实现房屋出租系统

1. 需求分析

  1. 实现基于文本界面的《房屋出租软件》
  2. 能够实现对房屋信息的添加、修改和删除(暂时用数组实现),并能够打印房屋明细表

2. 预期效果

预期效果可能和实际效果不同,预期效果只是为了描述需求

2.1 项目界面- 主菜单

image-20211214175425238

2.2 项目界面- 新增房源

image-20211214175525327

2.3 项目界面- 查找房源

2.4 项目界面- 删除房源

输入-1的时候退出,当然为了防止输错,还要确认一遍

image-20211214175537495

2.5 项目界面- 修改房源

修改每个状态,如果不希望修改某个信息,直接回车即可

image-20211214175542483

2.6 项目界面- 房屋列表

显示所有房屋

image-20211214175603600

2.7 项目界面- 退出系统

image-20211214175615087

3. 设计框架图

对比较复杂的软件,我们使用项目分层模式,画一个程序框架图,我们这里简单使用Xmind来呈现

image-20220106122649467

3.1 代码实现分析

4.基本类的实现

4.1 工具类-Utility

工具类的作用:

处理各种情况的用户输入,并且能够按照程序员的需求,得到用户的控制台输入

这里对于工具类的使用就不要求自己写了,因为主要是为了处理输入,这里用了一个Utility类

咱们直接把Utility当作api来使用

/**
	工具类的作用:
	处理各种情况的用户输入,并且能够按照程序员的需求,得到用户的控制台输入。
*/

import java.util.*;
/**

	
*/
public class Utility {
	//静态属性。。。
    private static Scanner scanner = new Scanner(System.in);

    
    /**
     * 功能:读取键盘输入的一个菜单选项,值:1——5的范围
     * @return 1——5
     */
	public static char readMenuSelection() {
        char c;
        for (; ; ) {
            String str = readKeyBoard(1, false);//包含一个字符的字符串
            c = str.charAt(0);//将字符串转换成字符char类型
            if (c != '1' && c != '2' && 
                c != '3' && c != '4' && c != '5') {
                System.out.print("选择错误,请重新输入:");
            } else break;
        }
        return c;
    }

	/**
	 * 功能:读取键盘输入的一个字符
	 * @return 一个字符
	 */
    public static char readChar() {
        String str = readKeyBoard(1, false);//就是一个字符
        return str.charAt(0);
    }
    /**
     * 功能:读取键盘输入的一个字符,如果直接按回车,则返回指定的默认值;否则返回输入的那个字符
     * @param defaultValue 指定的默认值
     * @return 默认值或输入的字符
     */
    
    public static char readChar(char defaultValue) {
        String str = readKeyBoard(1, true);//要么是空字符串,要么是一个字符
        return (str.length() == 0) ? defaultValue : str.charAt(0);
    }
	
    /**
     * 功能:读取键盘输入的整型,长度小于2位
     * @return 整数
     */
    public static int readInt() {
        int n;
        for (; ; ) {
            String str = readKeyBoard(10, false);//一个整数,长度<=10位
            try {
                n = Integer.parseInt(str);//将字符串转换成整数
                break;
            } catch (NumberFormatException e) {
                System.out.print("数字输入错误,请重新输入:");
            }
        }
        return n;
    }
    /**
     * 功能:读取键盘输入的 整数或默认值,如果直接回车,则返回默认值,否则返回输入的整数
     * @param defaultValue 指定的默认值
     * @return 整数或默认值
     */
    public static int readInt(int defaultValue) {
        int n;
        for (; ; ) {
            String str = readKeyBoard(10, true);
            if (str.equals("")) {
                return defaultValue;
            }
			
			//异常处理...
            try {
                n = Integer.parseInt(str);
                break;
            } catch (NumberFormatException e) {
                System.out.print("数字输入错误,请重新输入:");
            }
        }
        return n;
    }

    /**
     * 功能:读取键盘输入的指定长度的字符串
     * @param limit 限制的长度
     * @return 指定长度的字符串
     */

    public static String readString(int limit) {
        return readKeyBoard(limit, false);
    }

    /**
     * 功能:读取键盘输入的指定长度的字符串或默认值,如果直接回车,返回默认值,否则返回字符串
     * @param limit 限制的长度
     * @param defaultValue 指定的默认值
     * @return 指定长度的字符串
     */
	
    public static String readString(int limit, String defaultValue) {
        String str = readKeyBoard(limit, true);
        return str.equals("")? defaultValue : str;
    }


	/**
	 * 功能:读取键盘输入的确认选项,Y或N
	 * 将小的功能,封装到一个方法中.
	 * @return Y或N
	 */
    public static char readConfirmSelection() {
        System.out.println("请输入你的选择(Y/N)");
        char c;
        for (; ; ) {//无限循环
        	//在这里,将接受到字符,转成了大写字母
        	//y => Y n=>N
            String str = readKeyBoard(1, false).toUpperCase();
            c = str.charAt(0);
            if (c == 'Y' || c == 'N') {
                break;
            } else {
                System.out.print("选择错误,请重新输入:");
            }
        }
        return c;
    }

    /**
     * 功能: 读取一个字符串
     * @param limit 读取的长度
     * @param blankReturn 如果为true ,表示 可以读空字符串。 
     * 					  如果为false表示 不能读空字符串。
     * 			
	 *	如果输入为空,或者输入大于limit的长度,就会提示重新输入。
     * @return
     */
    private static String readKeyBoard(int limit, boolean blankReturn) {
        
		//定义了字符串
		String line = "";

		//scanner.hasNextLine() 判断有没有下一行
        while (scanner.hasNextLine()) {
            line = scanner.nextLine();//读取这一行
           
			//如果line.length=0, 即用户没有输入任何内容,直接回车
			if (line.length() == 0) {
                if (blankReturn) return line;//如果blankReturn=true,可以返回空串
                else continue; //如果blankReturn=false,不接受空串,必须输入内容
            }

			//如果用户输入的内容大于了 limit,就提示重写输入  
			//如果用户如的内容 >0 <= limit ,我就接受
            if (line.length() < 1 || line.length() > limit) {
                System.out.print("输入长度(不能大于" + limit + ")错误,请重新输入:");
                continue;
            }
            break;
        }

        return line;
    }
}

由于这个类的方法都是static的所以可以直接调用

4.2 House类

分析一下House类的属性,起码要有如下几个属性

编号房主电话地址月租状态(未出租/已出租)

我们设置属性为私有,同时提供构造器和Getter and Setter方法

同时为了方便输出,我们重写一下toString方法

public class House {
    //编号 房主 电话 地址 月租 状态(未出租/已出租)
private int id;
private String name;
private String phone;
private String address;
private int rent;
private String state;

    public House(int id, String name, String phone, String address, int rent, String state) {
        this.id = id;
        this.name = name;
        this.phone = phone;
        this.address = address;
        this.rent = rent;
        this.state = state;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public int getRent() {
        return rent;
    }

    public void setRent(int rent) {
        this.rent = rent;
    }

    public String getState() {
        return state;
    }

    public void setState(String state) {
        this.state = state;
    }

    @Override
    public String toString() {
        return          id +
                "\t" + name +
                "\t" + phone +
                "\t" + address +
                "\t" + rent +
                "\t" + state ;
    }
}

4.3 实现菜单

菜单不用多说直接上代码

private boolean loop = true;
    private char key = ' ';

    public void mainMenu() {
        do {
            System.out.println("===========HouseRentSysMenu===========");
            System.out.println("\t\t1 add new estate");
            System.out.println("\t\t2 search an estate");
            System.out.println("\t\t3 delete estate information");
            System.out.println("\t\t4 modify estate information");
            System.out.println("\t\t5 display estate information");
            System.out.println("\t\t6 exit Sys");
            System.out.println("please enter you choice(1-6): ");
            key = Utility.readChar();
            switch (key) {
                case '1':
                    addHouse();
                    break;
                case '2':
                    findHouse();
                    break;
                case '3':
                    delHouse();
                    break;
                case '4':
                    update();
                    break;
                case '5':
                    listHouses();
                    break;
                case '6':
                    exit();
                    break;
            }
        } while (loop);
    }

5. 功能实现

5.1 显示房屋信息

显示房屋信息要有如下需求

image-20220106124958233

那么我们先在HouseService中实现House数组

    private House[] houses;

    public HouseService(int size) {
        houses = new House[size];//创建对象的时候指定数组的大小
        //测试一个大牛马对象
        houses[0]=new House(1,"大牛马","8848","海淀区",2500,"已出租");
    }
    public House[] list(){
        return houses;
    }

然后在HouseView中增加功能

 private HouseService houseService = new HouseService(10);

    public void listHouses() {
        System.out.println("===========List of houses ===========");
        System.out.println("id\t\tname\t\tphone\t\taddress\t\trent\t\tstate(vacant/leased)");
        House[] houses = houseService.list();
        for (House house : houses) {
            if(house==null){//防止输出null
                break;
            }
            System.out.println(house);
        }
        System.out.println("===========Displaying done===========");

    }

当前状态:

image-20220106131450052

5.2 增加新房屋信息

显示房屋信息要有如下需求

image-20220106132603042

那么我们先在HouseService中实现add方法,同时定义一个加法器

 private int idCounter = 1;//记录id的自增长器
 private int houseNum = 1;//记录有多少个房屋信息
public boolean add(House newHouse) {
        //判断是否可以继续添加
        if (houseNum == houses.length) {
            System.out.println("数组已满不能添加");
            return false;
        }
        //newHouse对象加入到数组之后
        houses[houseNum++] = newHouse;
        newHouse.setId(++idCounter);
        return true;
    }

然后在HouseView中增加功能

public void addHouse() {
        //id 有系统自动分配
        System.out.println("===========Adding new estates===========");
        System.out.print("name: ");
        String name=Utility.readString(8);
        System.out.print("phone: ");
        String phone = Utility.readString(12);
        System.out.print("address: ");
        String address = Utility.readString(16);
        System.out.print("rent: ");
        int rent = Utility.readInt();
        System.out.print("state: ");
        String state = Utility.readString(3);
        House newHouse = new House(0, name, phone, address, rent, state);
        if (houseService.add(newHouse)) {
            System.out.println("=============添加房屋成功============");
        } else {
            System.out.println("=============添加房屋失败============");
        }
    }

当前状态

image-20220106135233397

另外对于数组的扩容可以后期增加完善,比如说实现动态扩容,当然继续往后面学的话放进集合中就可以了

5.3 删除房屋信息

image-20220106192027093

HouseView中

   public void delHouse() {
        System.out.println("=============Delete estate Information============");
        System.out.print("Please enter the number of the house to be deleted (-1 exit): ");
        int delId = Utility.readInt();
        if (delId == -1) {
            System.out.println("give up delete");
            return;
        }
        //Otherwise use Utility method
        char choice = Utility.readConfirmSelection();
        if (choice == 'Y') {
            if (houseService.del(delId)) {
                System.out.println("delete success");
            } else {
                System.out.println("can't find the estate with Id you provided");
            }
        } else {
            System.out.println("give up delete");
        }
    }

HouseService中

 public boolean del(int delId) {
        //first find the estate that is designated
        int index = -1;
        for (int i = 0; i < houseNums; i++) {
            if (delId == houses[i].getId()) {
                index = i;
            }//遍历一遍看看找到的话把index换成i
        }
        if (index == -1) {//没找到
            return false;
        }
        for (int i = index; i < houseNums - 1; i++) {
            houses[i] = houses[i + 1];
        }//删除操作,从index开始,后面的覆盖前面的

        houses[--houseNums] = null;//当前存在的房屋信息的最后一个置空,并houseNums减少

        return true;
    }

效果:

image-20220106193008550

5.4 退出程序

直接使用Utility就可以了

  public  void exit(){
        char c=Utility.readConfirmSelection();
        if(c=='Y'){
            loop=false;
        }
    }

5.5 房屋信息查找

image-20220106193738206

HouseView中

 public void findHouse() {
        System.out.println("=============Finding estate Information============");
        System.out.print("Please enter the ID you are looking for:");
        int findId = Utility.readInt();
        //调用方法
        House house = houseService.findById(findId);
        if (house != null) {
            System.out.println(house);
        } else {
            System.out.println("============Not Found=============");
        }
    }

HouseService中

  public House findById(int findId) {
        for (int i = 0; i < houseNums; i++) {
            if (findId == houses[i].getId()) {
                return houses[i];
            }
        }
        return null;
    }

效果:

image-20220106194635649

当然也可以根据address来查找,这个本质是一样的,就不写了

5.6 房屋信息修改

image-20220106194946912

HouseView中

 public void update() {
        System.out.println("=============Modify estate Information============");
        System.out.println("Please select the estate Id to be modified (-1 indicates exit): ");
        int updateId = Utility.readInt();
        if (updateId == -1) {
            System.out.println("=============give up modifying============");
            return;
        }
        House house = houseService.findById(updateId);
        if (house == null) {
            System.out.println("The modified house id does not exist");
        }
        System.out.print("name(" + house.getName() + "): ");
        String name = Utility.readString(8, "");//这里如果用户直接回车表示不修改该信息,默认""
        if (!"".equals(name)) {//修改
            house.setName(name);
        }

        System.out.print("phone(" + house.getPhone() + "):");
        String phone = Utility.readString(12, "");
        if (!"".equals(phone)) {
            house.setPhone(phone);
        }
        System.out.print("address(" + house.getAddress() + "): ");
        String address = Utility.readString(18, "");
        if (!"".equals(address)) {
            house.setAddress(address);
        }
        System.out.print("rent(" + house.getRent() + "):");
        int rent = Utility.readInt(-1);
        if (rent != -1) {
            house.setRent(rent);
        }
        System.out.print("state(" + house.getState() + "):");
        String state = Utility.readString(3, "");
        if (!"".equals(state)) {
            house.setState(state);
        }
        System.out.println("=============modify successfully============");
    }

效果:

image-20220106200334763

6.小结

本项目的目的是回顾Java的基础语法,同时学习编程设计思想,本小项目还是很简单的,但是所谓“模式”的概念是很重要的

如果想要全代码的话可以访问我的GitHub https://github.com/Allen9012/JavaSE-

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

言之命至9012

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值