Java模仿微信實現零錢通簡易功能(兩種版本)

最近剛剛復習瞭一下Java的面向對象三大特性,這裡跟著hsp做個小零錢通實踐一下,以下記錄瞭學習和編寫過程

1. 需求描述

使用Java 開發零錢通項目, 模仿微信實現簡易功能,可以完成收益入賬,消費,查看明細,退出系統等功能,先按照一般方法寫,後期在改進為OOP

預期界面:(實際可能不同)

2. 需求分析

面對這樣一個需求,先化繁為簡

  1. 寫一個菜單
  2. 完成零錢通明細.
  3. 完成收益入賬
  4. 消費
  5. 退出
  6. 用戶輸入4退出時,給出提示”你確定要退出嗎? y/n”,必須輸入正確的y/n ,否則循環輸入指令,直到輸入y 或者 n
  7. 在收益入賬和消費時,判斷金額是否合理,並給出相應的提示

3. 實現零錢通主要功能

3.1 寫一個菜單

先完成顯示菜單,並可以選擇菜單,並且給出對應提示

    public static void main(String[] args) {
        // define related variables
        Scanner scanner = new Scanner(System.in);
        String key = "";
        boolean loop = true;
        do {
            System.out.println("==========Small Change Menu==========");
            System.out.println("\t\t\t1 show change details");
            System.out.println("\t\t\t2 income entry");
            System.out.println("\t\t\t3 consumption");
            System.out.println("\t\t\t4 exit");
            System.out.println("please choose 1-4:");
            key = scanner.next();
            //use switch to control
            switch (key) {
                case "1":
                    System.out.println("1  show change details");
                    break;
                case "2":
                    System.out.println("2 income entry");
                    break;
                case "3":
                    System.out.println("3 consumption");
                    break;
                case "4":
                    System.out.println("4 exit");
                    System.out.println(" you have exit the SmallChange");
                    loop = false;
                    break;
                default:
                    System.out.println("err please choose again");
            }
        } while (loop);
    }

3.2 零錢通明細

思路

(1) 可以把收益入賬和消費保存到數組

(2) 可以使用對象

(3) 簡單的話可以使用String拼接

這裡直接采取第三種方式

改變一下switch的case1

 String details = "-----------------零錢通明細------------------";
   case "1":
                    System.out.println(details);
                    break;

3.3 收益入賬

完成收益入賬

定義新的變量

 double money = 0;
        double balance = 0;
        Date date = null; // date 是 java.util.Date 類型,表示日期
        //if you don't like the default format of displaying date ,change it with sdf
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");

修改switch中的case2

 System.out.print("Income recorded amount:");
                    money = scanner.nextDouble();
                    //the range of money should be limited
                    //give the hits of the illegal money value 就直接break
                    balance += money;
                    //拼接收益入賬信息到 details
                    date = new Date(); //Get the current time
                    details += "\n收益入賬\t+" + money + "\t" + sdf.format(date)+ "\t" + balance;
                    break;

效果演示:

保證入賬>0

3.4 消費

定義新的變量

 String note = "";

修改switch中的case3

  case "3":
                    System.out.print("Consumption amount:");
                    money = scanner.nextDouble();
                    //the range of money should be limited
                    System.out.print("Consumption Description:");
                    note = scanner.next();
                    balance -= money;
                    //Splicing consumption information to details
                    date = new Date();//Get the current time
                    details += "\n"+note + "\t-" + money + "\t" + sdf.format(date) + "\t" + balance;
                    break;

效果演示:

3.5 用戶退出改進

給出確認,是否要退出

用戶輸入4退出時,給出提示”你確定要退出嗎? y/n”,必須輸入正確的y/n ,

否則循環輸入指令,直到輸入y 或者 n

(1) 定義一個變量 choice, 接收用戶的輸入

(2) 使用 while + break, 來處理接收到的輸入時 y 或者 n

(3) 退出while後,再判斷choice是y還是n ,就可以決定是否退出

(4) 建議一段代碼完成功能,不混在一起

          case "4":
                    String choice = "";
                    while (true) {
                        //The user is required to enter Y / N, otherwise it will cycle all the time
                        System.out.println("你確定要退出嗎? y/n");
                        choice = scanner.next();
                        if ("y".equals(choice) || "n".equals(choice)) {
                            break;
                        }
                        //scheme 2
//                        if("y".equals(choice)) {
//                            loop = false;
//                            break;
//                        } else if ("n".equals(choice)) {
//                            break;
//                        }
                    }
                    if (choice.equals("y")) {
                        loop = false;
                    }
                    break;

效果演示:

3.6 改進金額判斷

收入時

 if (money <= 0) {
                        System.out.println("The income entry amount must be greater than 0");
                        break;
                    }

支出時

   if (money <= 0 || money > balance) {
                        System.out.println("Your consumption amount should be 0-" + balance);
                        break;
                    }

效果演示

4. 面向過程版實現

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;
public class SmallChangeSys {
    // try to reduce complexity to simplicity
//1.  First complete the display menu,
// and you can select the menu to give the corresponding prompt
//2.  Complete change details
//3.  Complete income entry
//4.  consumption
//5.  exit
//6.  When the user enters 4 to exit, the prompt "are you sure you want to exit?
// Y / N" will be given. You must enter the correct Y / N,
// otherwise cycle the input instruction until y or n is entered
//7. When the income is recorded and consumed,
// judge whether the amount is reasonable and give corresponding tips
    public static void main(String[] args) {
        // define related variables
        Scanner scanner = new Scanner(System.in);
        String key = "";
        boolean loop = true;
        //2. complete the change details
        //(1) 可以把收益入賬和消費,保存到數組 (2) 可以使用對象 (3) 簡單的話可以使用String拼接
        String details = "-----------------Change details------------------";
        //3. complete income entry
        double money = 0;
        double balance = 0;
        Date date = null; // date 是 java.util.Date 類型,表示日期
        //if you don't like the default format of displaying date ,change it with sdf
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        //4. consumption
        //define new variable,store the reason why consume
        String note = "";
        do {
            System.out.println("\n==========Small Change Menu==========");
            System.out.println("\t\t\t1 show change details");
            System.out.println("\t\t\t2 income entry");
            System.out.println("\t\t\t3 consumption");
            System.out.println("\t\t\t4 exit");
            System.out.println("please choose 1-4:");
            key = scanner.next();
            //use switch to control
            switch (key) {
                case "1":
                    System.out.println(details);
                    break;
                case "2":
                    System.out.print("Income recorded amount:");
                    money = scanner.nextDouble();
                    //the range of money should be limited
                    //commonly use <if> to judge the wrong situation make the code easy to read
                    //give the hits of the illegal money value 就直接break
                    if (money <= 0) {
                        System.out.println("The income entry amount must be greater than 0");
                        break;
                    }
                    balance += money;
                    //Splicing consumption information to details
                    date = new Date(); //Get the current time
                    details += "\n" + "Income " + "\t" + "+" + money + "\t" + sdf.format(date) + "\t" + balance;
                    break;
                case "3":
                    System.out.print("Consumption amount:");
                    money = scanner.nextDouble();
                    //the range of money should be limited
                    if (money <= 0 || money > balance) {
                        System.out.println("Your consumption amount should be 0-" + balance);
                        break;
                    }
                    System.out.print("Consumption Description:");
                    note = scanner.next();
                    balance -= money;
                    //Splicing consumption information to details
                    date = new Date();//Get the current time
                    details += "\n" + note + "\t-" + money + "\t" + sdf.format(date) + "\t" + balance;
                    break;
                case "4":
                    String choice = "";
                    while (true) {
                        //The user is required to enter Y / N, otherwise it will cycle all the time
                        System.out.println("你確定要退出嗎? y/n");
                        choice = scanner.next();
                        if ("y".equals(choice) || "n".equals(choice)) {
                            break;
                        }
                        //scheme 2
//                        if("y".equals(choice)) {
//                            loop = false;
//                            break;
//                        } else if ("n".equals(choice)) {
//                            break;
//                        }
                    }
                    if (choice.equals("y")) {
                        loop = false;
                    }
                    break;
                default:
                    System.out.println("err please choose again");

            }
        } while (loop);
        System.out.println(" you have exit the SmallChange");
    }
}

5. 優化成OOP版

很多東西可以直接復制過來變成方法,把原來的改過來是簡單的

5.1 實現OOP版

那麼先有一個執行的主類SmallChangeSysApp

//Call the object directly and display the main menu
public class SmallChangeSysApp {
    public static void main(String[] args) {
        new SmallChangeSysOOP().mainMenu();
    }
}

還有一個類專門是對象,我們叫它為SmallChangeSysOOP

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;

/**
 * This class is used to complete various functions of zero money pass
 * Using OOP (object-oriented programming)
 * Each function corresponds to a method
 */
public class SmallChangeSysOOP {
    //basic variables
    boolean loop = true;
    Scanner scanner = new Scanner(System.in);
    String key = "";

    //display details
    String details = "-----------------Change details------------------";

    //income
    double money = 0;
    double balance = 0;
    Date date = null;
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");

    // consume
    String note = "";

    public void mainMenu() {
        do {

            System.out.println("\n================Small Change Menu(OOP)===============");
            System.out.println("\t\t\t1 show change details");
            System.out.println("\t\t\t2 income entry");
            System.out.println("\t\t\t3 consumption");
            System.out.println("\t\t\t4 exit");
            System.out.println("please choose 1-4:");
            key = scanner.next();

            switch (key) {
                case "1":
                    this.detail();
                    break;
                case "2":
                    this.income();
                    break;
                case "3":
                    this.pay();
                    break;
                case "4":
                    this.exit();
                    break;
                default:
                    System.out.println("Choose the wrong number please choose again");
            }

        } while (loop);
    }


    public void detail() {
        System.out.println(details);
    }

    public void income() {
        System.out.print("Income recorded amount:");
        money = scanner.nextDouble();

        if (money <= 0) {
            System.out.println("The income entry amount must be greater than 0");
            return; //exit and do not execute next sentence.change break to return
        }
        balance += money;
        date = new Date();
        details += "\nIncome \t+" + money + "\t" + sdf.format(date) + "\t" + balance;
    }

    public void pay() {
        System.out.print("Consumption amount:");
        money = scanner.nextDouble();
        if (money <= 0 || money > balance) {
            System.out.println("Your consumption amount should be 0-" + balance);
            return;
        }
        System.out.print("consumption description:");
        note = scanner.next();
        balance -= money;
        date = new Date();
        details += "\n" + note + "\t-" + money + "\t" + sdf.format(date) + "\t" + balance;
    }

    //退出
    public void exit() {
        //When the user enters 4 to exit, the prompt "are you sure you want to exit?
        // Y / N" will be given. You must enter the correct Y / n
        String choice = "";
        while (true) {
            System.out.println("are you really gonna exit? y/n");
            choice = scanner.next();
            if ("y".equals(choice) || "n".equals(choice)) {
                break;
            }
            //scheme 2
//                        if("y".equals(choice)) {
//                            loop = false;
//                            break;
//                        } else if ("n".equals(choice)) {
//                            break;
//                        }
        }
        if (choice.equals("y")) {
            loop = false;
        }
    }
}

5.2 OOP的好處

OOP版主函數很簡單,隻要new這個對象就可以瞭,關於這個對象的其他方法也好屬性也好,不用放在主函數裡面,那樣在主函數也可以自由加上想加得到內容,未來假如有他人要用,不用把整個文件拷過去,隻要把類交給對方即可,這樣擴展和可讀性大大提升,要加什麼功能就再寫方法原先的擴展功能很麻煩,要來回切

以上就是Java模仿微信實現零錢通簡易功能(兩種版本)的詳細內容,更多關於Java的資料請關註WalkonNet其它相關文章!

推薦閱讀: