Java基礎學習:尚矽谷 面向對象進階 客戶信息管理軟體

来源:https://www.cnblogs.com/Noiimplant/archive/2023/05/22/17420754.html
-Advertisement-
Play Games

### 1. Customer.java ``` package chapter07.pinExer; // 客戶類 public class Customer { private String name; private char gender; //性別 private int age; pri ...


1. Customer.java

package chapter07.pinExer;

// 客戶類
public class Customer {
    private String name;
    private char gender; //性別
    private int age;
    private String phone;
    private String email;

    // 構造器
    public Customer(){

    }
    public Customer(String name, char gender, int age, String phone, String email){
        this.name = name;
        this.age = age;
        this.gender = gender;
        this.phone = phone;
        this.email = email;
    }

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

    public String getName() {
        return name;
    }

    public void setGender(char gender) {
        this.gender = gender;
    }

    public char getGender() {
        return gender;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public int getAge() {
        return age;
    }

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

    public String getPhone() {
        return phone;
    }

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

    public String getEmail() {
        return email;
    }
}

2. CustomerList.java

package chapter07.pinExer;
// CustomerList為Customer對象管理模塊,內部使用數組管理一組Customer對象
public class CustomerList {
    private Customer[] customers;
    private int total = 0; // 最大長度

    public CustomerList(int totalCustomer){
        customers = new Customer[totalCustomer];
    }

    //添加成員,成功返回true,失敗返回false
    public boolean addCustomer(Customer customer){
        if(total < customers.length){
            customers[total] = customer;
            total++;
            return true;
        }
        return false;
    }

    // 替換,用參數customer替換數組中由index指定的對象
    public boolean replaceCustomer(int index, Customer cust){
        if(index >= 0 && index < total){
            customers[index] = cust;
            return true;
        }
        return false;
    }

    // 刪除,從數組中刪除index指定索引位置的客戶對象記錄
    public boolean deleteCustomer(int index){
        if(index >= 0 && index < total){
            for(int i = index; i < total; i++){
                customers[i] = customers[i+1];
            }

            //將最後一個有效位置的數值置空
            customers[total - 1] = null;
            total--;
            return true;
        }
        return false;
    }

    // 返回數組中記錄的所有客戶對象
    public Customer[] getAllCustomers(){
        Customer[] custs = new Customer[total];
        for(int i = 0; i < total; i++){
            custs[i] = customers[i];
        }
        return custs;
    }

    // 返回index指定索引位置客戶的記錄
    public Customer getCustomer(int index){
        if(index >=0 && index < total){
            return customers[index];
        }
        return null;
    }

    // 獲取客戶列表中有幾個客戶
    public int getTotal(){
        return total;
    }

}

CMUtility.java 工具類

package chapter07.pinExer;
import java.util.*;
public class CMUtility {
    private static Scanner scanner = new Scanner(System.in);
    /**
     用於界面菜單的選擇。該方法讀取鍵盤,如果用戶鍵入’1’-’5’中的任意字元,則方法返回。返回值為用戶鍵入字元。
     */
    public static char readMenuSelection() {
        char c;
        for (; ; ) {
            String str = readKeyBoard(1, false);
            c = str.charAt(0);
            if (c != '1' && c != '2' &&
                    c != '3' && c != '4' && c != '5') {
                System.out.print("選擇錯誤,請重新輸入:");
            } else break;
        }
        return c;
    }
    /**
     從鍵盤讀取一個字元,並將其作為方法的返回值。
     */
    public static char readChar() {
        String str = readKeyBoard(1, false);
        return str.charAt(0);
    }
    /**
     從鍵盤讀取一個字元,並將其作為方法的返回值。
     如果用戶不輸入字元而直接回車,方法將以defaultValue 作為返回值。
     */
    public static char readChar(char defaultValue) {
        String str = readKeyBoard(1, true);
        return (str.length() == 0) ? defaultValue : str.charAt(0);
    }
    /**
     從鍵盤讀取一個長度不超過2位的整數,並將其作為方法的返回值。
     */
    public static int readInt() {
        int n;
        for (; ; ) {
            String str = readKeyBoard(2, false);
            try {
                n = Integer.parseInt(str);
                break;
            } catch (NumberFormatException e) {
                System.out.print("數字輸入錯誤,請重新輸入:");
            }
        }
        return n;
    }
    /**
     從鍵盤讀取一個長度不超過2位的整數,並將其作為方法的返回值。
     如果用戶不輸入字元而直接回車,方法將以defaultValue 作為返回值。
     */
    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;
    }
    /**
     從鍵盤讀取一個長度不超過limit的字元串,並將其作為方法的返回值。
     */
    public static String readString(int limit) {
        return readKeyBoard(limit, false);
    }
    /**
     從鍵盤讀取一個長度不超過limit的字元串,並將其作為方法的返回值。
     如果用戶不輸入字元而直接回車,方法將以defaultValue 作為返回值。
     */
    public static String readString(int limit, String defaultValue) {
        String str = readKeyBoard(limit, true);
        return str.equals("")? defaultValue : str;
    }
    /**
     用於確認選擇的輸入。該方法從鍵盤讀取‘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;
    }

    private static String readKeyBoard(int limit, boolean blankReturn) {
        String line = "";

        while (scanner.hasNextLine()) {
            line = scanner.nextLine();
            if (line.length() == 0) {
                if (blankReturn) return line;
                else continue;
            }

            if (line.length() < 1 || line.length() > limit) {
                System.out.print("輸入長度(不大於" + limit + ")錯誤,請重新輸入:");
                continue;
            }
            break;
        }

        return line;
    }
}

4. CustomerView.java 主模塊

package chapter07.pinExer;

import chapter07.pinExer.Customer;

// 主模塊,負責菜單的顯示和處理用戶操作
public class CustomerView {
    int totalCustomers = 10;
    CustomerList customerList = new CustomerList(totalCustomers);
    // 進入主界面
    public void enterMainMenu(){
        boolean flag = true;
        while(flag){
            System.out.println("\n------------------拼電商管理系統------------------\n");
            System.out.println("                    1.添 加 客 戶");
            System.out.println("                    2.修 改 客 戶");
            System.out.println("                    3.刪 除 客 戶");
            System.out.println("                    4.客 戶 列 表");
            System.out.println("                    5.退       出\n");
            System.out.println("                    請選擇(1-5)");

            char key = CMUtility.readMenuSelection();

            switch(key){
                case '1':
                    addNewCustomer();
                    break;
                case '2':
                    modifyCustomer();;
                    break;
                case '3':
                    deleteCustomer();
                    break;
                case '4':
                    listAllCustomers();
                    break;
                case '5':
                    System.out.print("確認是否退出(Y/N):");
                    char isExit = CMUtility.readConfirmSelection();
                    if(isExit == 'Y'){
                        flag = false;
                    }
                    break;
            }
        }
    }
    private void addNewCustomer(){
        System.out.println("\n---------------------添加客戶---------------------");
        if (customerList.getTotal() >= totalCustomers) {
            System.out.println("----------------客戶列表已滿,無法添加---------------");
            return;
        }
        System.out.print("姓名:");
        String name = CMUtility.readString(10);
        System.out.print("性別:");
        char gender = CMUtility.readChar();
        System.out.print("年齡:");
        int age = CMUtility.readInt();
        System.out.print("電話:");
        String phone = CMUtility.readString(13);
        System.out.print("郵箱:");
        String email = CMUtility.readString(20);
        Customer cust = new Customer(name, gender, age, phone, email);
        boolean isAdded = customerList.addCustomer(cust);
        if (isAdded) {
            System.out.println("---------------------添加完成---------------------");
        } else {
            System.out.println("---------------------添加失敗---------------------");
        }
    }
    private void modifyCustomer(){
        System.out.println("\n---------------------修改客戶---------------------");
        while (true) {
            System.out.print("請選擇待修改客戶編號(-1退出):");
            int number = CMUtility.readInt();
            if (number == -1) {
                return; //如果輸入-1,則直接結束方法
            } else if (number <= 0 || number > customerList.getTotal()) {
                System.out.println("無法找到指定客戶!");
            } else {
                System.out.print("姓名(" + customerList.getCustomer(number - 1).getName() + "):");
                String newName = CMUtility.readString(10, customerList.getCustomer(number - 1).getName());
                System.out.print("性別(" + customerList.getCustomer(number - 1).getGender() + "):");
                char newGender = CMUtility.readChar(customerList.getCustomer(number - 1).getGender());
                System.out.print("性別(" + customerList.getCustomer(number - 1).getAge() + "):");
                int newAge = CMUtility.readInt(customerList.getCustomer(number - 1).getAge());
                System.out.print("電話(" + customerList.getCustomer(number - 1).getPhone() + "):");
                String newPhone = CMUtility.readString(13, customerList.getCustomer(number - 1).getPhone());
                System.out.print("郵箱(" + customerList.getCustomer(number - 1).getEmail() + "):");
                String newEmail = CMUtility.readString(20, customerList.getCustomer(number - 1).getEmail());

                Customer cust = new Customer(newName, newGender, newAge, newPhone, newEmail);
                boolean isReplaced = customerList.replaceCustomer(number - 1, cust);
                if (isReplaced) {
                    System.out.println("---------------------修改完成---------------------");
                } else {
                    System.out.println("---------------------無法修改---------------------");
                }
                return;
            }
        }
    }
    private void deleteCustomer(){
        System.out.println("\n---------------------刪除客戶---------------------");
        while (true) {
            System.out.print("請選擇待刪除客戶編號(-1退出):");
            int number = CMUtility.readInt();
            if (number == -1) {
                return; //如果輸入-1,則直接結束方法
            } else if (number <= 0 || number > customerList.getTotal()) {
                System.out.println("無法找到指定客戶!");
            } else {
                System.out.print("確認是否刪除(Y/N):");
                char isDelete = CMUtility.readConfirmSelection();
                if (isDelete == 'Y') {
                    boolean isDeleted = customerList.deleteCustomer(number - 1);
                    if (isDeleted) {
                        System.out.println("---------------------刪除完成---------------------");
                    } else {
                        System.out.println("---------------------刪除失敗---------------------");
                    }
                }
                return;
            }
        }

    }
    private void listAllCustomers(){
        System.out.println("----------------------------------客戶列表----------------------------------");
        if (customerList.getTotal() == 0) {
            System.out.println("沒有客戶記錄!");
        } else {
            System.out.println("編號\t\t姓名\t\t性別\t\t年齡\t\t電話\t\t\t\t郵箱");
            Customer[] custs = customerList.getAllCustomers();
            for (int i = 0; i < custs.length; i++) {
                System.out.println((i + 1) + "\t\t" + custs[i].getName() + "\t\t" + custs[i].getGender() + "\t\t"
                        + custs[i].getAge() + "\t\t" + custs[i].getPhone() + "\t\t" + custs[i].getEmail());
            }
        }
        System.out.println("--------------------------------客戶列表完成---------------------------------");
    }

    public static void main(String[] args) {
        CustomerView view = new CustomerView();
        view.enterMainMenu();
    }

}


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 視頻地址 # 1 Stream流概述 - 目的:簡化集合和數組操作的API,結合了Lambda表達式。 - Stream流式思想的核心: 1. 先得到集合或者數組的Stream流(就是一根傳送帶) 2. 把元素放上去 3. 用這個Stream流簡化的API來方便的操作元素 # 2 Stream流獲取 ...
  • ### 子類調用父類的方法的三種方式: - 父類名.方法名(self) - super(子類名,self).父類方法名() - super().父類方法名 註意:super()通過子類調用當前父類的方法,super預設會調用第一個父類的方法(適用於單繼承的多層繼承 如下代碼: ```python # ...
  • 話說兄弟們,女朋友生氣了都是怎麼哄的? 不會吧不會吧,不會有人還是單身狗吧! 算了,還是回到正題吧,再說我要挨打了~ 今天咱們來交流一下程式員是怎麼哄女朋友的,話不多說直接開始! 準備工作 1、環境 首先我們準備好環境和編輯器,我使用的是: Python 3.8 解釋器 Pycharm 編輯器 2、 ...
  • 雖然PDF文件適合用於列印和發佈,但不適合所有類型的文檔。例如,包含複雜圖表和圖形的文檔可能無法在PDF中呈現得很好。但是HTML文件可以在任何可運行瀏覽器的電腦上進行閱讀並顯示。並且HTML還具有占用伺服器資源較小,便於搜索引擎收錄的特點。那麼今天這篇文章就將展示如何通過Java應用程式將PDF ...
  • 你好!我是[@馬哥python說](https://www.zhihu.com/people/13273183132),一枚10年程式猿👨🏻‍💻,正在試錯用pyecharts開發可視化大屏的非常規排版。 以下,我用8種ThemeType展示的同一個可視化數據大屏。 **1、SHINE主題** ...
  • 前文我們說過了BIO,今天我們聊聊NIO。NIO 是什麼?NIO官方解釋它為New lO,由於其特性我們也稱之為,Non-Blocking IO。這是jdk1.4之後新增的一套IO標準。為什麼要用NIO呢?我們再簡單回顧下BIO:阻塞式IO,原理很簡單,其實就是多個端點與服務端進行通信時,每個客戶端 ...
  • # 前置需求 一臺電腦(我用的是Windows),有網 # 第一步:下載並安裝 去java官網下載開發版java(考慮到可能有小白,我暫且這麼說) java官網下載鏈接:https://www.oracle.com/java/technologies/downloads/ 寫隨筆時間為2023、05 ...
  • ## 初步瞭解 ### 總體架構設計 Mybatis 整體框架如下: ![img](https://zhangjiahao-blog.oss-cn-beijing.aliyuncs.com/picgo/202305161021323.png) ##### 介面層 MyBatis 和資料庫的交互有兩種 ...
一周排行
    -Advertisement-
    Play Games
  • Dapr Outbox 是1.12中的功能。 本文只介紹Dapr Outbox 執行流程,Dapr Outbox基本用法請閱讀官方文檔 。本文中appID=order-processor,topic=orders 本文前提知識:熟悉Dapr狀態管理、Dapr發佈訂閱和Outbox 模式。 Outbo ...
  • 引言 在前幾章我們深度講解了單元測試和集成測試的基礎知識,這一章我們來講解一下代碼覆蓋率,代碼覆蓋率是單元測試運行的度量值,覆蓋率通常以百分比表示,用於衡量代碼被測試覆蓋的程度,幫助開發人員評估測試用例的質量和代碼的健壯性。常見的覆蓋率包括語句覆蓋率(Line Coverage)、分支覆蓋率(Bra ...
  • 前言 本文介紹瞭如何使用S7.NET庫實現對西門子PLC DB塊數據的讀寫,記錄了使用電腦模擬,模擬PLC,自至完成測試的詳細流程,並重點介紹了在這個過程中的易錯點,供參考。 用到的軟體: 1.Windows環境下鏈路層網路訪問的行業標準工具(WinPcap_4_1_3.exe)下載鏈接:http ...
  • 從依賴倒置原則(Dependency Inversion Principle, DIP)到控制反轉(Inversion of Control, IoC)再到依賴註入(Dependency Injection, DI)的演進過程,我們可以理解為一種逐步抽象和解耦的設計思想。這種思想在C#等面向對象的編 ...
  • 關於Python中的私有屬性和私有方法 Python對於類的成員沒有嚴格的訪問控制限制,這與其他面相對對象語言有區別。關於私有屬性和私有方法,有如下要點: 1、通常我們約定,兩個下劃線開頭的屬性是私有的(private)。其他為公共的(public); 2、類內部可以訪問私有屬性(方法); 3、類外 ...
  • C++ 訪問說明符 訪問說明符是 C++ 中控制類成員(屬性和方法)可訪問性的關鍵字。它們用於封裝類數據並保護其免受意外修改或濫用。 三種訪問說明符: public:允許從類外部的任何地方訪問成員。 private:僅允許在類內部訪問成員。 protected:允許在類內部及其派生類中訪問成員。 示 ...
  • 寫這個隨筆說一下C++的static_cast和dynamic_cast用在子類與父類的指針轉換時的一些事宜。首先,【static_cast,dynamic_cast】【父類指針,子類指針】,兩兩一組,共有4種組合:用 static_cast 父類轉子類、用 static_cast 子類轉父類、使用 ...
  • /******************************************************************************************************** * * * 設計雙向鏈表的介面 * * * * Copyright (c) 2023-2 ...
  • 相信接觸過spring做開發的小伙伴們一定使用過@ComponentScan註解 @ComponentScan("com.wangm.lifecycle") public class AppConfig { } @ComponentScan指定basePackage,將包下的類按照一定規則註冊成Be ...
  • 操作系統 :CentOS 7.6_x64 opensips版本: 2.4.9 python版本:2.7.5 python作為腳本語言,使用起來很方便,查了下opensips的文檔,支持使用python腳本寫邏輯代碼。今天整理下CentOS7環境下opensips2.4.9的python模塊筆記及使用 ...