练习题:试使用编程实现银行、ATM等功能
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApp3 { class Program { static void Main(string[] args) { //创建账户wangcehnjun Account wangchenjun = new Account("wangchenjun", "123456"); //创建账户niejiong Account niejiong = new Account("niejiong", "789456"); //创建ATM机Transfer1 ATM Transfer1 =new ATM(); //用户wangchenjun存入余额100万元 wangchenjun.toDeposit(1000000); Console.WriteLine("wangchenjun用户的余额为: {0}元",wangchenjun.getBalance()); //使用ATM机Transfer1,从用户wangchenjun向用户niejiong转账500元 if (Transfer1.toTransfer(wangchenjun, niejiong, 500)) Console.WriteLine("转账已完成!"); else Console.WriteLine("转账未完成!"); //用户wangchenjun取出50元现金 wangchenjun.toTakeOut(50); Console.WriteLine("wangchenjun用户的余额为:{0}元",wangchenjun.getBalance()); Console.WriteLine("niejiong用户的余额为:{0}元", niejiong.getBalance()); Console.ReadKey(); } } class Account { //用户名 private string userName = ""; //用户密码 private string userPassword = ""; //用户余额(balance) private int userBalance = 0; //创建账号,构造函数,输入姓名和密码 public Account(string name, string password) { userName = name; userPassword = password; } //获取该账户的用户名 public string getUserName() { return userName; } //获取账户余额 public int getBalance() { return userBalance; } //存钱 public bool toDeposit(int numOfDeposit) { if (numOfDeposit >= 0) //存储金额为正数 { userBalance = userBalance + numOfDeposit; return true; } else { return false; } } //取钱 public bool toTakeOut(int numOfTakeOut) { if ((numOfTakeOut >= 0) && (numOfTakeOut <=userBalance)) //要保证取钱数为正数,且要小于余额 { userBalance = userBalance - numOfTakeOut; return true; } else return false; } } class ATM { //ATM主要用于转账,该类只包含转账这一种方法 public bool toTransfer(Account account1,Account account2,int amount) { bool isTakeOutOK = account1.toTakeOut(amount); if (isTakeOutOK) { Console.Write("账户1({0})转出{1}元成功!",account1.getUserName(), amount); bool isDepositOK = account2.toDeposit(amount); if (isDepositOK) { Console.Write("账户2({0})转入{1}元成功!", account2.getUserName(),amount); return true; } else { account1.toDeposit(amount); //将扣的钱退回到account1 Console.Write("转账失败!"); return false; } } else { Console.Write("转账失败!"); return false; } } } }
运行结果: