题目:
代码实现:
BankAccount部分:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;namespace Bank
{internal class BankAccount{private decimal balance = 0;//账户余额public static bool accountOK = true;public string Name { get; set; }public decimal Balance{get{return balance;}set{if(value>=0){balance = value;}else{Console.WriteLine("余额有误!!!");accountOK = false;}}}public BankAccount(string name,decimal initiaBalance)//构造函数{Name = name;Balance = initiaBalance;}public void Deposit(BankAccount a){decimal cun;Console.WriteLine("存款金额:");cun = decimal.Parse(Console.ReadLine());a.Balance += cun;Console.WriteLine($"账户余额:{balance}");}public void Withdraw(BankAccount a){decimal num;Console.WriteLine("取款金额:");num = decimal.Parse(Console.ReadLine());if(num>a.balance){Console.WriteLine("余额不足!!!");}else{a.balance -= num;}}public void Display(BankAccount a){Console.WriteLine($"账户:{Name}\t余额:{a.balance}");}}
}
注意点:
balance的赋值过程,用value来判断输入的是否合法,判断的是value不是balance(判断完value之后才使用value给balance赋值)
program部分:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;namespace Bank
{internal class Program{static void menu(){Console.WriteLine("存钱输入'0',取钱输入'1',结束输入'2'");}static void Main(string[] args){string name;decimal qian = 0;char op;Console.WriteLine("姓名:");name = Console.ReadLine();Console.WriteLine("初始余额:");qian = decimal.Parse(Console.ReadLine());BankAccount account = new BankAccount(name, qian);if(BankAccount.accountOK) do{menu();op = char.Parse(Console.ReadLine());switch (op){case '0':account.Deposit(account);break;case '1':account.Withdraw(account);if (BankAccount.accountOK)account.Display(account);break;case '2':BankAccount.accountOK = false;break;}}while (BankAccount.accountOK);}}
}
end......