银行管理系统C++代码转Java代码9_16

C++代码源自《C++语言程序设计(第4版)》(清华大学计算机系列教材) 郑莉, 董渊, 何江舟 清华大学出版社

9_16

C++源码

//9_16.cpp
#include "account.cpp"
#include "Array.h"
#include <iostream>
using namespace std;

int main() {
	Date date(2008, 11, 1);	//起始日期
	Array<Account *> accounts(0);	//创建账户数组,元素个数为0
	cout << "(a)add account (d)deposit (w)withdraw (s)show (c)change day (n)next month (e)exit" << endl;
	char cmd;
	do {
		//显示日期和总金额
		date.show();
		cout << "\tTotal: " << Account::getTotal() << "\tcommand> ";

		char type;
		int index, day;
		double amount, credit, rate, fee;
		string id, desc;
		Account* account;

		cin >> cmd;
		switch (cmd) {
		case 'a':	//增加账户
			cin >> type >> id;
			if (type == 's') {
				cin >> rate;
				account = new SavingsAccount(date, id, rate);
			} else {
				cin >> credit >> rate >> fee;
				account = new CreditAccount(date, id, credit, rate, fee);
			}
			accounts.resize(accounts.getSize() + 1);
			accounts[accounts.getSize() - 1] = account;
			break;
		case 'd':	//存入现金
			cin >> index >> amount;
			getline(cin, desc);
			accounts[index]->deposit(date, amount, desc);
			break;
		case 'w':	//取出现金
			cin >> index >> amount;
			getline(cin, desc);
			accounts[index]->withdraw(date, amount, desc);
			break;
		case 's':	//查询各账户信息
			for (int i = 0; i < accounts.getSize(); i++) {
				cout << "[" << i << "] ";
				accounts[i]->show();
				cout << endl;
			}
			break;
		case 'c':	//改变日期
			cin >> day;
			if (day < date.getDay())
				cout << "You cannot specify a previous day";
			else if (day > date.getMaxDay())
				cout << "Invalid day";
			else
				date = Date(date.getYear(), date.getMonth(), day);
			break;
		case 'n':	//进入下个月
			if (date.getMonth() == 12)
				date = Date(date.getYear() + 1, 1, 1);
			else
				date = Date(date.getYear(), date.getMonth() + 1, 1);
			for (int i = 0; i < accounts.getSize(); i++)
				accounts[i]->settle(date);
			break;
		}
	} while (cmd != 'e');

	for (int i = 0; i < accounts.getSize(); i++)
		delete accounts[i];

	return 0;
}


//Array.h
#ifndef ARRAY_H
#define ARRAY_H

#include <cassert>

//数组类模板定义
template <class T> 
class Array {
private:
	T* list;	//T类型指针,用于存放动态分配的数组内存首地址
	int size;	//数组大小(元素个数)
public:
	Array(int sz = 50);			//构造函数
	Array(const Array<T> &a);	//拷贝构造函数
	~Array();	//析构函数
	Array<T> & operator = (const Array<T> &rhs); //重载"="使数组对象可以整体赋值
	T & operator [] (int i);	//重载"[]",使Array对象可以起到C++普通数组的作用
	const T & operator [] (int i) const;	//"[]"运算符的const版本
	operator T * ();	//重载到T*类型的转换,使Array对象可以起到C++普通数组的作用
	operator const T * () const;	//到T*类型转换操作符的const版本
	int getSize() const;	//取数组的大小
	void resize(int sz);	//修改数组的大小
};

//构造函数
template <class T>
Array<T>::Array(int sz) {
	assert(sz >= 0);	//sz为数组大小(元素个数),应当非负
	size = sz;	// 将元素个数赋值给变量size
	list = new T [size];	//动态分配size个T类型的元素空间
}

//析构函数
template <class T>
Array<T>::~Array() {
	delete [] list;
}

//拷贝构造函数
template <class T>
Array<T>::Array(const Array<T> &a) {
	//从对象x取得数组大小,并赋值给当前对象的成员
	size = a.size;
	//为对象申请内存并进行出错检查
	list = new T[size];	// 动态分配n个T类型的元素空间
	//从对象X复制数组元素到本对象  
	for (int i = 0; i < size; i++)
		list[i] = a.list[i];
}

//重载"="运算符,将对象rhs赋值给本对象。实现对象之间的整体赋值
template <class T>
Array<T> &Array<T>::operator = (const Array<T>& rhs) {
	if (&rhs != this) {
		//如果本对象中数组大小与rhs不同,则删除数组原有内存,然后重新分配
		if (size != rhs.size) {
			delete [] list;		//删除数组原有内存
			size = rhs.size;	//设置本对象的数组大小
			list = new T[size];	//重新分配n个元素的内存
		}
		//从对象X复制数组元素到本对象  
		for (int i = 0; i < size; i++)
			list[i] = rhs.list[i];
	}
	return *this;	//返回当前对象的引用
}

//重载下标运算符,实现与普通数组一样通过下标访问元素,并且具有越界检查功能
template <class T>
T &Array<T>::operator[] (int n) {
	assert(n >= 0 && n < size);	//检查下标是否越界
	return list[n];			//返回下标为n的数组元素
}

template <class T>
const T &Array<T>::operator[] (int n) const {
	assert(n >= 0 && n < size);	//检查下标是否越界
	return list[n];			//返回下标为n的数组元素
}

//重载指针转换运算符,将Array类的对象名转换为T类型的指针,
//指向当前对象中的私有数组。
//因而可以象使用普通数组首地址一样使用Array类的对象名
template <class T>
Array<T>::operator T * () {
	return list;	//返回当前对象中私有数组的首地址
}

template <class T>
Array<T>::operator const T * () const {
	return list;	//返回当前对象中私有数组的首地址
}

//取当前数组的大小
template <class T>
int Array<T>::getSize() const {
	return size;
}

// 将数组大小修改为sz
template <class T>
void Array<T>::resize(int sz) {
	assert(sz >= 0);	//检查sz是否非负
	if (sz == size)	//如果指定的大小与原有大小一样,什么也不做
		return;
	T* newList = new T [sz];	//申请新的数组内存
	int n = (sz < size) ? sz : size;	//将sz与size中较小的一个赋值给n
	//将原有数组中前n个元素复制到新数组中
	for (int i = 0; i < n; i++)
		newList[i] = list[i];
	delete[] list;		//删除原数组
	list = newList;	// 使list指向新数组
	size = sz;	//更新size
}
#endif  //ARRAY_H

//account.cpp
#include "account.h"
#include <cmath>
#include <iostream>
using namespace std;

double Account::total = 0;

//Account类的实现
Account::Account(const Date &date, const string &id)
	: id(id), balance(0) {
	date.show();
	cout << "\t#" << id << " created" << endl;
}

void Account::record(const Date &date, double amount, const string &desc) {
	amount = floor(amount * 100 + 0.5) / 100;	//保留小数点后两位
	balance += amount;
	total += amount;
	date.show();
	cout << "\t#" << id << "\t" << amount << "\t" << balance << "\t" << desc << endl;
}

void Account::show() const {
	cout << id << "\tBalance: " << balance;
}

void Account::error(const string &msg) const {
	cout << "Error(#" << id << "): " << msg << endl;
}

//SavingsAccount类相关成员函数的实现
SavingsAccount::SavingsAccount(const Date &date, const string &id, double rate)
	: Account(date, id), rate(rate), acc(date, 0) { }

void SavingsAccount::deposit(const Date &date, double amount, const string &desc) {
	record(date, amount, desc);
	acc.change(date, getBalance());
}

void SavingsAccount::withdraw(const Date &date, double amount, const string &desc) {
	if (amount > getBalance()) {
		error("not enough money");
	} else {
		record(date, -amount, desc);
		acc.change(date, getBalance());
	}
}

void SavingsAccount::settle(const Date &date) {
	if (date.getMonth() == 1) {	//每年的一月计算一次利息
		double interest = acc.getSum(date) * rate
			/ (date - Date(date.getYear() - 1, 1, 1));
		if (interest != 0)
			record(date, interest, "interest");
		acc.reset(date, getBalance());
	}
}

//CreditAccount类相关成员函数的实现
CreditAccount::CreditAccount(const Date& date, const string& id, double credit, double rate, double fee)
	: Account(date, id), credit(credit), rate(rate), fee(fee), acc(date, 0) { }

void CreditAccount::deposit(const Date &date, double amount, const string &desc) {
	record(date, amount, desc);
	acc.change(date, getDebt());
}

void CreditAccount::withdraw(const Date &date, double amount, const string &desc) {
	if (amount - getBalance() > credit) {
		error("not enough credit");
	} else {
		record(date, -amount, desc);
		acc.change(date, getDebt());
	}
}

void CreditAccount::settle(const Date &date) {
	double interest = acc.getSum(date) * rate;
	if (interest != 0)
		record(date, interest, "interest");
	if (date.getMonth() == 1)
		record(date, -fee, "annual fee");
	acc.reset(date, getDebt());
}

void CreditAccount::show() const {
	Account::show();
	cout << "\tAvailable credit:" << getAvailableCredit();
}

//account.h
#ifndef __ACCOUNT_H__
#define __ACCOUNT_H__
#include "date.cpp"
#include "accumulator.h"
#include <string>

class Account { //账户类
private:
	std::string id;	//帐号
	double balance;	//余额
	static double total; //所有账户的总金额
protected:
	//供派生类调用的构造函数,id为账户
	Account(const Date &date, const std::string &id);
	//记录一笔帐,date为日期,amount为金额,desc为说明
	void record(const Date &date, double amount, const std::string &desc);
	//报告错误信息
	void error(const std::string &msg) const;
public:
	const std::string &getId() const { return id; }
	double getBalance() const { return balance; }
	static double getTotal() { return total; }
	//存入现金,date为日期,amount为金额,desc为款项说明
	virtual void deposit(const Date &date, double amount, const std::string &desc) = 0;
	//取出现金,date为日期,amount为金额,desc为款项说明
	virtual void withdraw(const Date &date, double amount, const std::string &desc) = 0;
	//结算(计算利息、年费等),每月结算一次,date为结算日期
	virtual void settle(const Date &date) = 0;
	//显示账户信息
	virtual void show() const;
};

class SavingsAccount : public Account { //储蓄账户类
private:
	Accumulator acc;	//辅助计算利息的累加器
	double rate;		//存款的年利率
public:
	//构造函数
	SavingsAccount(const Date &date, const std::string &id, double rate);
	double getRate() const { return rate; }
	virtual void deposit(const Date &date, double amount, const std::string &desc);
	virtual void withdraw(const Date &date, double amount, const std::string &desc);
	virtual void settle(const Date &date);
};

class CreditAccount : public Account { //信用账户类
private:
	Accumulator acc;	//辅助计算利息的累加器
	double credit;		//信用额度
	double rate;		//欠款的日利率
	double fee;			//信用卡年费

	double getDebt() const {	//获得欠款额
		double balance = getBalance();
		return (balance < 0 ? balance : 0);
	}
public:
	//构造函数
	CreditAccount(const Date &date, const std::string &id, double credit, double rate, double fee);
	double getCredit() const { return credit; }
	double getRate() const { return rate; }
	double getFee() const { return fee; }
	double getAvailableCredit() const {	//获得可用信用
		if (getBalance() < 0)
			return credit + getBalance();
		else
			return credit;
	}
	virtual void deposit(const Date &date, double amount, const std::string &desc);
	virtual void withdraw(const Date &date, double amount, const std::string &desc);
	virtual void settle(const Date &date);
	virtual void show() const;
};

#endif //__ACCOUNT_H__

//date.cpp
#include "date.h"
#include <iostream>
#include <cstdlib>
using namespace std;

namespace {	//namespace使下面的定义只在当前文件中有效
	//存储平年中某个月1日之前有多少天,为便于getMaxDay函数的实现,该数组多出一项
	const int DAYS_BEFORE_MONTH[] = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 };
}

Date::Date(int year, int month, int day) : year(year), month(month), day(day) {
	if (day <= 0 || day > getMaxDay()) {
		cout << "Invalid date: ";
		show();
		cout << endl;
		exit(1);
	}
	int years = year - 1;
	totalDays = years * 365 + years / 4 - years / 100 + years / 400
		+ DAYS_BEFORE_MONTH[month - 1] + day;
	if (isLeapYear() && month > 2) totalDays++;
}

int Date::getMaxDay() const {
	if (isLeapYear() && month == 2)
		return 29;
	else
		return DAYS_BEFORE_MONTH[month]- DAYS_BEFORE_MONTH[month - 1];
}

void Date::show() const {
	cout << getYear() << "-" << getMonth() << "-" << getDay();
}

//date.h
#ifndef __DATE_H__
#define __DATE_H__

class Date {	//日期类
private:
	int year;		//年
	int month;		//月
	int day;		//日
	int totalDays;	//该日期是从公元元年1月1日开始的第几天

public:
	Date(int year, int month, int day);	//用年、月、日构造日期
	int getYear() const { return year; }
	int getMonth() const { return month; }
	int getDay() const { return day; }
	int getMaxDay() const;		//获得当月有多少天
	bool isLeapYear() const {	//判断当年是否为闰年
		return year % 4 == 0 && year % 100 != 0 || year % 400 == 0;
	}
	void show() const;			//输出当前日期
	//计算两个日期之间差多少天	
	int operator - (const Date& date) const {
		return totalDays - date.totalDays;
	}
};

#endif //__DATE_H__

//accumulator.h
#ifndef __ACCUMULATOR_H__
#define __ACCUMULATOR_H__
#include "date.h"

class Accumulator {	//将某个数值按日累加
private:
	Date lastDate;	//上次变更数值的时期
	double value;	//数值的当前值
	double sum;		//数值按日累加之和
public:
	//构造函数,date为开始累加的日期,value为初始值
	Accumulator(const Date &date, double value)
		: lastDate(date), value(value), sum(0) { }

	//获得到日期date的累加结果
	double getSum(const Date &date) const {
		return sum + value * (date - lastDate);
	}

	//在date将数值变更为value
	void change(const Date &date, double value) {
		sum = getSum(date);
		lastDate = date;
		this->value = value;
	}

	//初始化,将日期变为date,数值变为value,累加器清零
	void reset(const Date &date, double value) {
		lastDate = date;
		this->value = value;
		sum = 0;
	}
};

#endif //__ACCUMULATOR_H__

C++运行结果

9_16C++运行结果

Java代码

//Test.java
import java.util.Scanner;
import java.util.ArrayList;
import java.io.*;
public class Test {

	public static void main(String[] args) {
		Date date=new Date(2008, 11, 1);	//起始日期	
		ArrayList<Account> accounts=new ArrayList<Account>();//创建账户数组,元素个数为0
		System.out.println("(a)add account (d)deposit (w)withdraw (s)show (c)change day (n)next month (e)exit");
		char cmd='0';
		Scanner sc = new Scanner(System.in);
		do {
			//显示日期和总金额
			date.show();
			System.out.println("\tTotal: "+Account.getTotal()+"\tcommand> ");
			
			char type='0';
			int index, day;
			double amount, credit, rate, fee;
			String id, desc;
			System.out.println("请输入指令 cmd:");
			cmd= sc.next().charAt(0);
			switch (cmd) {
			case 'a':	//增加账户
				try {
					System.out.println("请输入账户类型(s:SavingAccount 其它:CreditAccount):");
					type=(char) System.in.read();
				} catch (IOException e) {
					e.printStackTrace();
				}
				System.out.println("请输入id:");
				 id=sc.next();
				if (type == 's') {
					System.out.println("请输入存款的年利率rate:");
				 rate=sc.nextDouble();
					accounts.add(new SavingsAccount(date, id, rate));
				} else {
					System.out.println("请输入信用额度credit:");
					credit=sc.nextDouble();
					System.out.println("请输入欠款的日利率rate:");
                    rate=sc.nextDouble(); 
                    System.out.println("请输入信用卡年费fee:");
                    fee=sc.nextDouble();
                    accounts.add(new CreditAccount(date, id, credit, rate, fee));
				}
				break;
			case 'd':	//存入现金
				System.out.println("请输入账户数组下标index:");
				index=sc.nextInt();
				System.out.println("请输入存款金额amount:");
				amount=sc.nextDouble();
				System.out.println("请输入存款项目名称desc:");
				desc=sc.nextLine();
				accounts.get(index).deposit(date, amount, desc);
				break;
			case 'w':	//取出现金
				System.out.println("请输入账户数组下标index:");
				index=sc.nextInt();
				System.out.println("请输入取款金额amount:");
				amount=sc.nextDouble();
				System.out.println("请输入取款项目名称desc:");
				desc=sc.nextLine();
				accounts.get(index).withdraw(date, amount, desc);
				break;
			case 's':	//查询各账户信息
				for (int i = 0; i <accounts.size(); i++) {
					System.out.print("[" + i + "] ");
					accounts.get(i).show();
					System.out.println();
				}
				break;
			case 'c':	//改变日期
				System.out.println("请输入日期day:");
				day=sc.nextInt();
				if (day < date.getDay())
					System.out.println("You cannot specify a previous day");
				else if (day> date.getMaxDay())
					System.out.println("Invalid day");
				else
					date = new Date(date.getYear(), date.getMonth(), day);
				break;
			case 'n':	//进入下个月
				if (date.getMonth() == 12)
					date = new Date(date.getYear() + 1, 1, 1);
				else
					date = new Date(date.getYear(), date.getMonth() + 1, 1);
				for (int i = 0; i < accounts.size(); i++)
					accounts.get(i).settle(date);
				break;
			}
		} while (cmd != 'e');
		sc.close();
		accounts.clear();
	}
}

//Account.java
public abstract class Account {
	private String id;	//帐号
	private double balance;	//余额
	private static double total=0; //所有账户的总金额
	final String getId() { return id; }
	final double getBalance() {	return balance;}
	static double getTotal() {	return total;}

	protected Account(final Date date, final String id){
		this.id=id;
		this.balance=0; 
		date.show();
		System.out.println("\t#" + id + "created");
	}

	protected void record(final Date date, double amount,final String desc) {
		amount =Math.floor((amount * 100 + 0.5) / 100);// 保留小数点后两位
		balance += amount;
		total += amount;
		date.show();
		System.out.println("\t#" + id + "\t" + amount + "\t" + balance + "\t" + desc);
	}

	void show() {
		System.out.print(id + "\tBalance: " + balance);
	}
	//存入现金,date为日期,amount为金额,desc为款项说明
	abstract void deposit(final Date date, double amount, final String desc);
		//取出现金,date为日期,amount为金额,desc为款项说明
	abstract void withdraw(final Date date, double amount, final String desc);
		//结算(计算利息、年费等),每月结算一次,date为结算日期
	abstract void settle(final Date date);
		//显示账户信息

	protected final void error(final String msg)  {
		System.out.println("Error(#" + id + "): " + msg +"\n");
	}

}

//CreditAccount.java
public class CreditAccount extends Account {
	//CreditAccount类相关成员函数的实现//信用账户类
	private Accumulator acc;	//辅助计算利息的累加器
	private double credit;		//信用额度
	private double rate;		//欠款的日利率
	private double fee;			//信用卡年费

	final private double getDebt()  {	//获得欠款额
			double balance = getBalance();
			return (balance < 0 ? balance : 0);
		}
	CreditAccount(final Date date, final String id, double credit, double rate, double fee)
	{	super(date, id);
		this.credit=credit;
		this.rate=rate;
		this.fee=fee;
		this.acc=new Accumulator(date, 0);
	}
		//构造函数
		final double getCredit()  { return credit; }
		final double getRate(){ return rate; }
		final double getFee() { return fee; }
		final double getAvailableCredit() {	//获得可用信用
			if (getBalance() < 0) 
				return credit + getBalance();
			else
				return credit;
		}
		
		// 存入现金
		void deposit(final Date date, double amount,final String desc) {
			record(date, amount,desc);
			acc.change(date, getDebt());
		}

		// 取出现金
		void withdraw(final Date date, double amount,final String desc) {
			if (amount - getBalance() > credit) {
				error("not enough credit");
			} else {
				record(date, -amount, desc);
				acc.change(date, getDebt());
			}
		}

		// 结算利息,每年1月1日调用一次该函数
		void settle(final Date date) {
			double interest = acc.getSum(date) * rate;
			if (interest != 0)
				record(date, interest, "interest");
			if (date.getMonth() == 1)
				record(date, -fee, "annual fee");
			acc.reset(date, getDebt());
		}


	final void show(){
		super.show();
		System.out.println("\tAvailable credit:" + getAvailableCredit());
	}

}

//SavingsAccount.java
public class SavingsAccount extends Account {

	private Accumulator acc;	//辅助计算利息的累加器
	private double rate;		//存款的年利率
	final double getRate() { return rate; }
	// 构造函数
	SavingsAccount(final Date date, String id, double rate) {
		super(date, id);
		this.rate=rate;
		this.acc=new Accumulator(date, 0);
	}
	// 存入现金
	void deposit(final Date date, double amount,final String desc) {
		record(date, amount, desc);
		acc.change(date, getBalance());
	}

	// 取出现金
	void withdraw(final Date date, double amount,final String desc) {
		if (amount > getBalance()) {
			error("not enough money");
		} else {
			record(date, -amount, desc);
			acc.change(date, getBalance());
		}
	}

	// 结算利息,每年1月1日调用一次该函数
	void settle(final Date date) {
		if (date.getMonth() == 1) {	//每年的一月计算一次利息
			double interest = acc.getSum(date) * rate
				/ (date.getTotalDays() - (new Date(date.getYear() - 1, 1, 1)).getTotalDays());
			if (interest != 0)
				record(date, interest, "interest");
			acc.reset(date, getBalance());
	}

}}

//Date.java
public class Date {
	// 存储平年中某个月1日之前有多少天,为便于getMaxDay函数的实现,该数组多出一项
	final int[] DAYS_BEFORE_MONTH = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 };
	private int year; // 年
	private int month; // 月
	private int day; // 日
	private int totalDays; // 该日期是从公元元年1月1日开始的第几天

	public Date(int year, int month, int day) {
		this.year = year;
		this.month = month;
		this.day = day;
		if (day <= 0 || day > getMaxDay()) {
			System.out.println("Invalid date: ");
			show();
			System.out.println();
			System.exit(1);
		}
		int years = year - 1;
		totalDays = years * 365 + years / 4 - years / 100 + years / 400 + DAYS_BEFORE_MONTH[month - 1] + day;
		if (isLeapYear() && month > 2)
			totalDays++;
	}// 用年、月、日构造日期

	final int getYear() {
		return year;
	}
	int getTotalDays() {
		return this.totalDays;
	}

	final int getMonth() {
		return month;
	}

	final int getDay() {
		return day;
	}

	final int getMaxDay() {
			if (isLeapYear() && month == 2)
				return 29;
			else
				return DAYS_BEFORE_MONTH[month]- DAYS_BEFORE_MONTH[month - 1];
		}; // 获得当月有多少天

	final boolean isLeapYear() {	//判断当年是否为闰年
			return year % 4 == 0 && year % 100 != 0 || year % 400 == 0;
		}

	final void show() {
		System.out.print( getYear()+ "-" + getMonth()+"-" + getDay());//输出当前日期
	}
		//计算两个日期之间差多少天	

}

//Accumulator.java
public class Accumulator {
//将某个数值按日累加
	private Date lastDate; // 上次变更数值的时期
	private double value; // 数值的当前值
	private double sum; // 数值按日累加之和
	// 构造函数,date为开始累加的日期,value为初始值

	Accumulator(final Date date, double value) {
		this.lastDate = date;
		this.value = value;
		this.sum = 0;
	}

	// 获得到日期date的累加结果
	final double getSum(final Date date) {
		return sum + value * (date.getTotalDays()-lastDate.getTotalDays());
	}

	// 在date将数值变更为value
	void change(final Date date, double value) {
		sum = getSum(date);
		lastDate = date;
		this.value = value;
	}

	// 初始化,将日期变为date,数值变为value,累加器清零
	void reset(final Date date, double value) {
		lastDate = date;
		this.value = value;
		sum = 0;
	}
}

Java运行结果

9_16Java运行结果

posted @ 2019-10-13 10:44  MY知北  阅读(242)  评论(0编辑  收藏  举报