1. 程式人生 > 實用技巧 >Java基礎之:客戶資訊管理軟體(CRM)

Java基礎之:客戶資訊管理軟體(CRM)

Java基礎之:客戶資訊管理軟體(CRM)

實際執行效果

新增客戶:

顯示客戶列表:

修改使用者:

刪除使用者:

實際程式碼

程式設計思路:

檔案分層

程式碼實現

Customer.java

package crm.domain;
/**
 * 		資料層/domain,javabean,pojo
 */

	
public class Customer {
	// 編號   姓名       性別    年齡   電話   郵箱
	private int id;
	private String name;
	private char sex;
	private int age;
	private String phone;
	private String email;
	
	public Customer(int id, String name, char sex, int age, String phone, String email) {
		super();
		this.id = id;
		this.name = name;
		this.sex = sex;
		this.age = age;
		this.phone = phone;
		this.email = email;
	}
	
	public String getPhone() {
		return phone;
	}

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

	public Customer() {
		super();
	}

	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 char getSex() {
		return sex;
	}
	public void setSex(char sex) {
		this.sex = sex;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}

	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}

	@Override
	public String toString() {
		return  id + "\t" + name + "\t" + sex + "\t" + age + "\t" + phone
				+ "\t" + email ;
	}
	
	
}

  

CustomerService.java

package crm.service;

import crm.domain.Customer;
import crm.utils.CMUtility;
/**
 * 		業務處理層
 */
public class CustomerService {
	
	//將所有物件儲存在一個數組中,customers[]
	Customer[] customers;
	int  customerNum = 1; //用於記錄,目前有幾個人在陣列中
	int  customerId = 1 ; //用於標記新增使用者的編號。
	
	public CustomerService(int len) {	//構造器 傳入預設陣列長度,即人數
		customers = new Customer[len];
		//先預設生成一個人,用於測試
		customers[0] = new Customer(1, "小范", '男', 20, "1112", "[email protected]");
	}
	
	//返回陣列列表
	public Customer[] list() {
		return customers;
	}
	
	//新增使用者,加入陣列擴容的功能
	public boolean addCustomer(Customer customer) {
		
		//新增進customers陣列中
		if(customerNum >= customers.length) { //已存在人數小於陣列長度,可以新增
			System.out.println("陣列已滿..");	
			
			//這裡陣列擴容
			Customer[] temp = new Customer[customers.length + 1];
			for (int i = 0; i < customers.length; i++) {
				temp[i] = customers[i];
			}
			
			customer.setId(++customerId);	//此使用者的id 為 以前的id+1
			temp[customers.length] = customer;
			
			customers = temp;
			
			return true;
		}
		
		customer.setId(++customerId);	//此使用者的id 為 以前的id+1
		customers[customerNum++] = customer; // 每新增一個使用者,讓陣列內人數++
		
		return true;
	}
	
	//刪除使用者,指定id
	public boolean delCustomer(int id) {
		int index = -1 ; //儲存要刪除id的下標
		for (int i = 0; i < customerNum; i++) {
			if(customers[i].getId() == id) {
				index  = i ;
			}
		}
		
		if(index == -1) {
			return false;
		}else {
			for(int i = index;i < customerNum;i++) {
				//將要刪除客戶後面的客戶依次前移
				customers[i] = customers[i + 1];
			}
			//將customerNum所在的客戶置空,因為已經前移了
			customers[customerNum--] = null;	//同時要減少陣列中的人數
			return true;
		}
	}

	//修改使用者資訊,將新物件賦值給原來的位置
	public boolean changeCustomer(int id,Customer customer) {
		int index = -1 ; //儲存要賦值id的下標
		for (int i = 0; i < customerNum; i++) {
			if(customers[i].getId() == id) {
				index  = i ;
			}
		}
		
		if(index == -1) {
			return false;
		}else {
			customers[index] = customer;
			return true;
		}
	}

	//判斷使用者是否存在,返回查詢到的使用者
	public Customer customerIsIn(int id) {
		int index = -1 ; 
		for (int i = 0; i < customerNum; i++) {
			if(customers[i].getId() == id) {
				index  = i ;
			}
		}
		if(index == -1) {
			return null;
		}else {
			return customers[index];
		}
	}
}

  

CustomerView.java

package crm.view;
/**
 *  	介面層
 */

import crm.domain.Customer;
import crm.service.CustomerService;
import crm.utils.CMUtility;

public class CustomerView {
	
	//建立物件,呼叫Service功能
	private CustomerService customerService = new CustomerService(2);
	
	public static void main(String[] args) {
		new CustomerView().showMenu();
	}
	
	//列印選單
	public void showMenu(){ 
		boolean flag = true;
		do {
			/*
			 * -----------------客戶資訊管理軟體-----------------
			 
                            1 添 加 客 戶
                            2 修 改 客 戶
                            3 刪 除 客 戶
                            4 客 戶 列 表
                            5 退           出

                            請選擇(1-5):_

			 */
			
			System.out.println("\n===================客戶資訊管理軟體===================");
			System.out.println("\t\t1 添 加 客 戶");
			System.out.println("\t\t2 修 改 客 戶");
			System.out.println("\t\t3 刪 除 客 戶");
			System.out.println("\t\t4 客 戶 列 表");
			System.out.println("\t\t5 退           出");
			System.out.print("請選擇(1-5):");
			char choice = CMUtility.readMenuSelection();
			
			switch(choice) {
				case '1':
					add();
					break;
				case '2':
					change();
					break;
				case '3':
					del();
					break;
				case '4':
					showList();
					break;
				case '5':
					System.out.println("退      出");
					flag = false;
					break;
			}
		} while (flag);
	}
	
	//顯示客戶列表,即輸出所有客戶資訊
	public void showList() {
		Customer[] customers = customerService.list();
		/*
		 * ---------------------------客戶列表---------------------------
			編號  姓名       性別    年齡   電話            郵箱
			 1    張三       男      30     010-56253825   [email protected]
			 2    李四       女      23     010-56253825    [email protected]
			 3    王芳       女      26     010-56253825   [email protected]
			-------------------------客戶列表完成-------------------------

		 */
		System.out.println("=======================客戶列表=======================");
		System.out.println("編號\t姓名\t性別\t年齡\t電話\t郵箱");
		for (int i = 0; i < customers.length; i++) {
			if (customers[i] == null) {
				break;
			}
			System.out.println(customers[i]);
		}
		System.out.println("======================客戶列表完成=====================");
	}
	
	//新增客戶
	public void add() {
		/*
		 * ---------------------新增客戶---------------------
			姓名:張三
			性別:男
			年齡:30
			電話:010-56253825
			郵箱:[email protected]
			---------------------新增完成---------------------

		 */
		
		System.out.println("=======================新增客戶=======================");
		System.out.print("姓名:");
		String name = CMUtility.readString(10);
		System.out.print("性別:");
		char sex = CMUtility.readChar();
		System.out.print("年齡:");
		int age = CMUtility.readInt();
		System.out.print("電話:");
		String phone = CMUtility.readString(12);
		System.out.print("郵箱:");
		String email = CMUtility.readString(20);
		
		Customer customer = new Customer(0, name, sex, age, phone, email);
		
		if(customerService.addCustomer(customer)) {
			System.out.println("=======================新增成功=======================");
		}else {
			System.out.println("=======================新增失敗=======================");
		}
	}

	//刪除使用者
	public void del() {
		/*
		 * ---------------------刪除客戶---------------------
			請選擇待刪除客戶編號(-1退出):1
			確認是否刪除(Y/N):y
		   ---------------------刪除完成---------------------
		 */
		System.out.println("\n=======================刪除客戶=======================");
		System.out.print("請選擇待刪除客戶編號(-1退出):");
		int id = CMUtility.readInt();
		System.out.print("確認是否刪除(Y/N):");
		char flag = CMUtility.readConfirmSelection();
		if(flag == 'Y') {
			if(customerService.delCustomer(id)) {
				System.out.println("=======================刪除成功=======================");
			}else {
				System.out.println("=======================刪除失敗=======================");
			}
		}else {
			System.out.println("=======================取消刪除=======================");
		}
		
	}

	//修改客戶
	public void change() {
		/*
		 * ---------------------修改客戶---------------------
			請選擇待修改客戶編號(-1退出):1
			姓名(張三):<直接回車表示不修改>
			性別(男):
			年齡(30):
			電話(010-56253825):
			郵箱([email protected]):[email protected]
			---------------------修改完成---------------------
		 */
		
		System.out.println("\n=======================修改客戶=======================");
		System.out.print("請選擇待修改客戶編號(-1退出):");
		int id = CMUtility.readInt();
		Customer findCustomer = customerService.customerIsIn(id);//儲存返回的客戶物件
		if(findCustomer == null) {	//如果id不存在直接提示輸入錯誤,修改失敗
			System.out.println("=================修改失敗,輸入id錯誤=================");
		}else {	//id存在
			System.out.print("姓名("+ findCustomer.getName() +"):<直接回車表示不修改>");
			String name = CMUtility.readString(10, findCustomer.getName());
			System.out.print("性別("+ findCustomer.getSex() +"):");
			char sex = CMUtility.readChar(findCustomer.getSex());
			System.out.print("年齡("+ findCustomer.getAge() +"):");
			int  age = CMUtility.readInt(findCustomer.getAge());
			System.out.print("電話("+ findCustomer.getPhone() +"):");
			String phone = CMUtility.readString(12,findCustomer.getPhone());
			System.out.print("郵箱("+ findCustomer.getEmail() +"):");
			String email = CMUtility.readString(20,findCustomer.getEmail());
			Customer customer = new Customer(id, name, sex, age, phone, email);
			if(customerService.changeCustomer(id, customer)) {
				System.out.println("=======================修改成功=======================");
			}else {
				System.out.println("=======================修改失敗=======================");
			}
		}
	}
}

  

CMUility.java(工具包)

package crm.utils;

/**
	工具類的作用:
	處理各種情況的使用者輸入,並且能夠按照程式設計師的需求,得到使用者的控制檯輸入。
*/

import java.util.*;
/**

	
*/
public class CMUtility {
	//靜態屬性。。。
    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(2, 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() {
        char c;
        for (; ; ) {
            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;
    }
}