Go-家庭收支软件(面向对象)很重要

记账软件 面向对象

image

image

main.go

package main

import (
	"fmt"
	"go_code/family/utils"
)

func main() {
	fmt.Println("这个是面向对象的方式完成~")
	utils.NewFamilyAccount().MainMenu()
}

familyAccount.go

package utils

import "fmt"

type FamilyAccount struct {
	key     string
	loop    bool
	balance float64
	money   float64
	note    string
	count   bool
	details string
}

//编写要给工厂模式的构造方法,返回一个*FamilyAccount实例
func NewFamilyAccount() *FamilyAccount {
	return &FamilyAccount{
		key:     "",
		loop:    true,
		balance: 10000.0,
		count:   false,
		money:   0.0,
		note:    "",
		details: "收支\t账户金额\t收支金额\t说明",
	}
}

func (t *FamilyAccount) showDetails() {
	fmt.Println("-------当前收支明细记录---------")
	if !t.count {
		fmt.Println("当前没有收支明细")
	} else {
		fmt.Println(t.details)
	}
}

func (t *FamilyAccount) income() {
	fmt.Println("本次收入金额:")
	fmt.Scanln(&t.money)
	t.balance += t.money
	fmt.Println("本次收入说明:")
	fmt.Scanln(&t.note)
	t.details += fmt.Sprintf("\n收入\t%v\t\t%v\t\t%v", t.balance, t.money, t.note)
	t.count = true
}

func (t *FamilyAccount) pay() {
	fmt.Println("本次支出金额:")
	fmt.Scanln(&t.money)
	if t.money > t.balance {
		fmt.Println("余额不足")
		return
	}
	t.balance -= t.money
	fmt.Println("本次支出说明:")
	fmt.Scanln(&t.note)
	t.details += fmt.Sprintf("\n支出\t%v\t\t%v\t\t%v", t.balance, t.money, t.note)
	t.count = true
}
func (t *FamilyAccount) exit() {
	fmt.Println("你确定要退出吗?y/n")
	flag := ""
	for {

		fmt.Scanln(&flag)
		if flag == "y" {
			t.loop = false
			break
		} else if flag == "n" {
			break
		} else {
			fmt.Println("你的输入有误,请重新输入 y/n")
		}
	}
}

func (t *FamilyAccount) MainMenu() {
	for {
		fmt.Println("\n-----------家庭收支记账软件-------------")
		fmt.Println("             1.收支明细")
		fmt.Println("             2.登记收入")
		fmt.Println("             3.登记支出")
		fmt.Println("             4.退出软件")
		fmt.Println("请选择(1-4)")
		fmt.Scanln(&t.key)
		switch t.key {
		case "1":
			t.showDetails()
		case "2":
			t.income()
		case "3":
			t.pay()
		case "4":
			t.exit()
		default:
			fmt.Println("请输入正确的选项..")
		}
		if !t.loop {
			break
		}
	}
}

image

posted @ 2022-06-11 10:25  司砚章  阅读(34)  评论(0编辑  收藏  举报