Housing Rental System (First Edition)

Table of contents

first edition


first edition

Idea analysis:

This is a simple housing rental system in the first version. Because there is no collection or database learned, it can only be used. Arrays are used to store and save information. We can find in actual situations that when using arrays, there are many differences. For example, when adding and deleting houses, it is necessary to expand or delete the array, and to find out whether a house exists, it is necessary to traverse the entire array. If there are many elements in the array, the time spent on traversal is It will become longer and longer, thus reducing efficiency. Compared with the second edition, many disadvantages of the first edition are reflected

House class

This class defines some attributes needed for renting a house, such as number, name, phone number, address, rent, status of the house, etc.

package com.houserent.domain;

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 double 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\t" + name +
                "\t" + phone +
                "\t\t" + address +
                "\t\t" + rent +
                "\t\t" + state;
    }
}

HouseService class

Idea analysis:

This class has completed a bit, and we can see the various responses to the interface layer. In the first version, because we have not yet learned about collections and databases, we can only use an array to store content. Then when we need to add new houses At this time, it is equivalent to expanding the array. When deleting a house, it is equivalent to shrinking the opponent’s array. And there is a disadvantage of using the array, that is, we can’t control the number of the house.

2. Some details of the add method

If the currently recorded housing information is equal to the length of the array, it means that the array is full and needs to be expanded. 
Then we need to create an array that is 1 larger than the original array, and expand it whenever necessary. After the expansion, the 
original array The contents of the array are copied to the new array in turn 
, and then the original array points to the new array. At this time, the discarded space of the original array will be recycled.

package com.houserent.service;

import com.houserent.domain.House;

import java.util.Iterator;

public class HouseService {
    //属性
    private House[] houses;//声明一个数组   (保存数组对象)
    private int HouseNum = 1;//记录当前数组有多少个元素(记录当前有多少个房屋信息)
    private int idCount = 1;//记录当前的id增长到哪一个值了

    //构造器设置数组的大小
    public HouseService(int size) {
        //在创建HouseService 对象时指定数组的大小
        houses = new House[size];
        houses[0] = new House(1, "jack", "122", "杭州", 2000, "未出租");
    }

    //findid()方法返回类型为一个House 根据传进来的值判断有没有这个元素
    public House findbyid(int id) {
        for (int i = 0; i < HouseNum; i++) {
            if (id == houses[i].getId()) {
                return houses[i];
            }
        }
        return null;
    }


    //del方法根据id来删除数组里是否能删除
    public boolean del(int delid) {//接受传过来需要删除的id
        int index = -1;//定义一个旗帜
        for (int i = 0; i < HouseNum; i++) {//for循化遍历当前有几个房屋信息
            if (delid == houses[i].getId()) {//如果发现其中一个房屋信息和传进来需要删除的id相同那么就把当前i的值赋给index
                index = i;
            }
        }
        if (index == -1) {//如果在遍历过完之后发现index的值没有被修改那么说明,没有这个id所以直接返回一个false
            return false;
        }
        //这里必须要减1  因为如果不减1相当于把后面空的一个位置移动,会报空指针异常
        for (int i = index; i < HouseNum - 1; i++) {//如果找到了这个id那么就是把后一个元素的放到前一个地方去从要删除的id开始
            houses[i] = houses[i + 1];//把后一个元素赋给前面的元素
        }
        //HouseNum;
        houses[--HouseNum] = null;//把当前存在的最后一个元素置成空
        return true;
    }


    //findway查找方法根据id来查询数组里是否有这个信息返回类型为House,如果找到了返回直接返回,如果没有找到返回一个空
    public House findway(int findid) {
        for (int i = 0; i < houses.length; i++) {//for循化遍历如果发现有一个相同那么就直接返回
            if (findid == houses[i].getId()) {
                return houses[i];
            }
        }
        return null;//如果上面没有返回说明没有找到直接返回一个null
    }

    //add方法,添加新对象,返回一个布尔值
    public boolean add(House newHouse) {
        //当  当前记录的房屋信息和数组长度相等时,那么说明数组的已满需要扩容
        if (HouseNum == houses.length) {
            House housenew[] = new House[houses.length + 1];//创建一个比原来数组还要大1的数组,每当需要时就进行扩容
            for (int i = 0; i < houses.length; i++) {//扩容完之后把原来数组的内容依次拷贝到新数组里面去
                housenew[i] = houses[i];
            }
            houses = housenew;//让原来数组指向新数组,此时原来数组的空间废弃 会被回收
            //houses[HouseNum] = newHouse;
            //HouseNum++;
            //上面的这两句话也可以写成
            houses[HouseNum++] = newHouse;//把新添加进来的元素放到数组的最后面
            //因为id默认给的是0所以我们要自己设计一个id自增长的机制
            //idCount++;//在上面我们设置一个默认的元素所以id初始值的为1
            //newHouse.setId(idCount);
            //上面的这两句话可以写成效果相同
            newHouse.setId(++idCount);//因为每一次添加一个信息id都需要增加所以我们先++把值赋给id通过提供的set方法实现
            System.out.println("扩容成功");
        } else {//当不用扩容时走这里正常添加
            houses[HouseNum++] = newHouse;
            newHouse.setId(++idCount);
        }
        return true;
    }


    //编写一个list方法返回信息,返回类型是一个数组,也就是返回数组里的信息
    public House[] list() {
        return houses;
    }
}

HouseView class

This is an interface layer. Our menu interface is in this class, which uses a Boolean value loop to control the display of the menu, and has corresponding methods to interact with the Service layer.

package com.houserent.view;


import com.houserent.domain.House;
import com.houserent.service.HouseService;
import com.houserent.utils.Utility;
import com.sun.jmx.snmp.internal.SnmpAccessControlModel;

import java.util.Scanner;

public class HouseView {
    //属性
    private int a;//接受用户的输入
    private boolean loop = true;//控制显示菜单
    private HouseService houseService = new HouseService(1);//设置数组的大小

    //编写一个update方法
    public void update() {
        System.out.println("--------------修改信息--------------");
        System.out.println("请选择待修改的房屋编号(-1退出)");
        int b = Utility.readInt();
        if (b == -1) {//如果输入的值为-1就退出
            return;
        }
        //返回的是引用类型,就是数组的元素在后面set方法的时候会影响到数组的信息
        House house = houseService.findbyid(b);
        //调用findid方法判断要修改的编号存不存在
        if (house == null) {
            System.out.println("--------------要修改的信息不存在--------------");
            return;
        }

        System.out.print("姓名" + "(" + house.getName() + "):");
        String name = Utility.readString(8, "");//如果用户不输入信息直接回车,表示不修改信息默认为空
        if (!"".equals(name)) {//如果你输入的值不等于空,表示要修改z
            house.setName(name);
        }
        System.out.print("电话" + "(" + house.getPhone() + "):");
        String phone = Utility.readString(18, "1234567");
        if (!"".equals(phone)) {
            house.setPhone(phone);
        }
        System.out.print("地址" + "(" + house.getAddress() + "):");
        String address = Utility.readString(10, "");
        if (!"".equals(address)) {
            house.setAddress(address);
        }
        System.out.print("租金" + "(" + house.getRent() + "):");
        int rent = Utility.readInt(-1);//如果直接输入回车返回一个默认值要自己传默认值
        if (rent != -1) {
            house.setRent(rent);
        }
        System.out.print("状态" + "(" + house.getState() + "):");
        String state = Utility.readString(10, "");
        if (!"".equals(state)) {
            house.setState(state);
        }
    }


    //编写一个exit方法
    public void exit() {
        char keys = Utility.readConfirmSelection();
        if (keys == 'Y') {
            loop = false;
        }
    }

    //编写一个delHouse方法,接受del方法的返回值
    public void delHouese() {
        System.out.println("--------------删除房屋--------------");
        System.out.println("请选择删除房屋的编号(-1退出)");
        int num = Utility.readInt();
        if (num == -1) {//如果输入的值为-1就退出
            System.out.println("--------------放弃删除房屋信息--------------");
            return;
        }
        char key = Utility.readConfirmSelection();//接受一个字符必须为y或者n这个方法自带大小写转换
        if (key == 'Y') {//如果输入的为Y 表示真的删除
            if (houseService.del(num)) {//调用del()方法把要输入的编号传过去进行判断  返回类型是一个布尔值
                System.out.println("--------------删除房屋信息成功--------------");
            } else {
                System.out.println("--------------放弃删除房屋失败,房屋编号不存在 --------------");
            }
        } else {//表示放弃删除
            System.out.println("--------------放弃删除房屋信息--------------");
        }
    }


    //编写addHouse()接受输入,创建House对象,调用add方法
    public void addHouse() {
        System.out.println("--------------添加房屋--------------");
        //模仿界面提示相应的信息
        System.out.print("姓名: ");
        String name = Utility.readString(8);
        System.out.print("电话: ");
        String phone = Utility.readString(12);
        System.out.print("地址: ");
        String address = Utility.readString(16);
        System.out.print("月租: ");
        int rent = Utility.readInt();
        System.out.print("状态: ");
        String state = Utility.readString(3);

        House house = new House(0, name, phone, address, rent, state);
        if (houseService.add(house)) {
            System.out.println("--------------添加房屋成功--------------");
        } else {
            System.out.println("--------------添加房屋失败--------------");
        }

    }

    //编写find方法查找房屋信息
    public void find() {
        System.out.println("请输入你要查找房间的id号");
        int id = Utility.readInt();
        House a = houseService.findway(id);//定义一个House类型的变量接受findway()方法的返回值  在根据返回值进行判断是否找到
        if (a == null) {
            System.out.println("--------------改房间id不存在--------------");
        } else {
            System.out.println(a);
        }

    }

    //编写listHouses()显示房屋列表
    public void listHouses() {
        System.out.println("--------------房屋列表--------------");
        System.out.println("编号\t\t房主\t\t电话\t\t地址\t\t月租\t\t\t状态(未出租/已出租)");
        //得到数组的全部内容  因为我们在HouseService里写了一个list方法返回类型是一个数组 所以我们先接受数组在遍历数组
        House[] houses = houseService.list();//得到所以的房屋信息,也就是数组的全部内容
        for (int i = 0; i < houses.length; i++) {
            if (houses[i] == null) {//如果这个数组大小为3那么当这个数组里目前只有一个元素时另外几个元素显示的就是null 因此加一个判断如果为null了那么就不在继续显示了
                break;
            }
            System.out.println(houses[i]);
        }
        System.out.println("--------------房屋列表显示完毕--------------");
    }


    //显示菜单的方法
    public void printmenu() {
        do {
            System.out.println("\n--------------房屋出租系统菜单--------------");
            System.out.println("\t\t\t1.新 增 房 源");
            System.out.println("\t\t\t2.查 找 房 屋");
            System.out.println("\t\t\t3.删 除 房 屋");
            System.out.println("\t\t\t4.修 改 房 屋 信 息");
            System.out.println("\t\t\t5.房 屋 列 表");
            System.out.println("\t\t\t6.退      出");
            System.out.println("请输入你的选择");

            a = Utility.readInt();
            switch (a) {
                case 1:
                    addHouse();//1.新 增 房 源
                    break;
                case 2:
                    find();//2.查 找 房 屋
                    break;
                case 3:
                    delHouese();//3.删 除 房 屋
                    break;
                case 4:
                    update();
                    //System.out.println("4.修 改 房 屋 信 息");
                    break;
                case 5:
                    listHouses();//显示房屋列表
                    break;
                case 6:
                    exit();//6.退      出
                    return;
                default:
                    System.out.println("你输入的有误");
                    break;
            }
        } while (loop);
    }
}

HouseRentApp class

This class is to call the interface layer, so that the program can run

package com.houserent;

import com.houserent.domain.House;
import com.houserent.view.HouseView;

public class HouseRentApp {
    public static void main(String[] args) {
        new HouseView().printmenu();
        System.out.println("--------------你退出了房屋出租系统--------------");
//        House house = new House("jack", "122", "杭州", 2000, "未出租");
//        System.out.println(house);

    }
}

Utility class

Code demo:

package item.HousingRentalSystem.utils;


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

import java.util.Scanner;

/**


 */
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(2, false);//一个整数,长度<=2位
            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.print("确认是否预定(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;
    }
}

Guess you like

Origin blog.csdn.net/weixin_53616401/article/details/129841242