wtx2333

实现效果:

代码:
FamilyAccount.go实现:

package utils
import "fmt"

type FamilyAccount struct{
key string
loop bool
balance float32
money float32
note string
flag bool
detail string
}

//返回一个FamilyAccount护实例
func NewFamilyAccount() *FamilyAccount{
return &FamilyAccount{
key:"",
loop:true,
balance:10000.0,
money:0.0,
note:"",
flag:false,
detail:"收支\t账户金额\t收支金额\t说明",
}
}

//给结构体绑定相应的方法
//将显示明细封装到一个方法
func (this *FamilyAccount )showDetails(){
fmt.Println("------------当前收支明细-----------------")
if this.flag{
fmt.Println(this.detail)
}else{
fmt.Println("当前还没有明细....")
}
}
//
func (this *FamilyAccount )addAccount(){
fmt.Print("本次收入金额:")
fmt.Scanln(&this.money)
fmt.Print("本次收入说明:")
fmt.Scanln(&this.note)
this.balance+=this.money
this.detail+=fmt.Sprintf("\n收入\t%v\t\t%v\t\t%v",this.balance,this.money,this.note)
this.flag=true
}
//
func (this *FamilyAccount )pay(){
fmt.Print("本次支出金额:")
fmt.Scanln(&this.money)
if this.money>this.balance{
fmt.Println("超出金额")
return
}
fmt.Print("本次支出说明:")
fmt.Scanln(&this.note)
this.balance-=this.money
this.detail+=fmt.Sprintf("\n支出\t%v\t\t%v\t\t%v",this.balance,this.money,this.note)
this.flag=true
}
//
func (this *FamilyAccount )quit(){
fmt.Print("确定退出吗?y/n:")
choice:=""
for{
fmt.Scanln(&choice)
if choice"y"||choice"n"{
break
}
fmt.Println("请重新输入。。。。")
fmt.Print("确定退出吗?y/n:")
}
if choice=="y"{
this.loop=false
}
}

//显示主菜单
func (this *FamilyAccount)MainMenu(){
for{
fmt.Println("")
fmt.Println("--------------家庭收支记账系统-----------------------")
fmt.Println(" 1.收支明细")
fmt.Println(" 2. 登记收入")
fmt.Println(" 3. 登记支出")
fmt.Println(" 4. 退出系统")
fmt.Print("请选择(1-4):")
fmt.Scanln(&this.key)
switch this.key{
case "1":
this.showDetails()

	case "2":
		this.addAccount()
    case "3":
		this.pay()
	case "4":
		this.quit()	
	default:
		fmt.Println("请输入正确的选项..")
	}
	if !this.loop{
		break
	}
}
fmt.Println("已退出系统.....")

}

main.go实现:

package main

import "go_code/project01/utils"

func main(){
utils.NewFamilyAccount().MainMenu()
}

心得:
刚接触go,感觉是C和python的结合(虽然python没咋学。。。
声明变量不需要数据类型
条件语句条件没有小括号
结构体声明变量是变量名 类型
语句后面不需要加分号

分类:

技术点:

相关文章: