katharsis

写在前面:

要求:
1、 模仿个人银行账户管理系统的C++版本(第4章-第8章),使用Java语言重新实现该系统,比较C++与Java在实现上的异同,熟练掌握Java基础及语法。
2、 根据系统需求的演化,逐步完善个人银行账户管理系统的功能,改进代码,体会面向对象思想的封装、继承、多态特性在实际系统中的应用,初步掌握使用Java编写可复用、可扩展、可维护代码的基本技能。

本文是本人根据已有的C++代码,用Java重写个人银行管理系统并实现其相应的功能。

 

1.0版本

需求分析:(初级)实现银行账户开户、存款、取钱、结算利息,输出余额等。

 以下是C++代码:

 1 //4_9.cpp
 2 #include <iostream>
 3 #include <cmath>
 4 using namespace std;
 5 
 6 class SavingsAccount { //储蓄账户类
 7 private:
 8     int id;                //账号
 9     double balance;        //余额
10     double rate;        //存款的年利率
11     int lastDate;        //上次变更余额的时期
12     double accumulation;    //余额按日累加之和
13 
14     //记录一笔帐,date为日期,amount为金额,desc为说明
15     void record(int date, double amount);
16     //获得到指定日期为止的存款金额按日累积值
17     double accumulate(int date) const {
18         return accumulation + balance * (date - lastDate);
19     }
20 public:
21     //构造函数
22     SavingsAccount(int date, int id, double rate);
23     int getId() { return id; }
24     double getBalance() { return balance; }
25     double getRate() { return rate; }
26 
27     //存入现金
28     void deposit(int date, double amount);
29     //取出现金
30     void withdraw(int date, double amount);
31     //结算利息,每年1月1日调用一次该函数
32     void settle(int date);
33     //显示账户信息
34     void show();
35 };
36 
37 //SavingsAccount类相关成员函数的实现
38 SavingsAccount::SavingsAccount(int date, int id, double rate)
39     : id(id), balance(0), rate(rate), lastDate(date), accumulation(0) {
40     cout << date << "\t#" << id << " is created" << endl;
41 }
42 
43 void SavingsAccount::record(int date, double amount) {
44     accumulation = accumulate(date);
45     lastDate = date;
46     amount = floor(amount * 100 + 0.5) / 100;    //保留小数点后两位
47     balance += amount;
48     cout << date << "\t#" << id << "\t" << amount << "\t" << balance << endl;
49 }
50 
51 void SavingsAccount::deposit(int date, double amount) {
52     record(date, amount);
53 }
54 
55 void SavingsAccount::withdraw(int date, double amount) {
56     if (amount > getBalance())
57         cout << "Error: not enough money" << endl;
58     else
59         record(date, -amount);
60 }
61 
62 void SavingsAccount::settle(int date) {
63     double interest = accumulate(date) * rate / 365;    //计算年息
64     if (interest != 0)
65         record(date, interest);
66     accumulation = 0;
67 }
68 
69 void SavingsAccount::show() {
70     cout << "#" << id << "\tBalance: " << balance;
71 }
72 
73 int main() {
74     //建立几个账户
75     SavingsAccount sa0(1, 21325302, 0.015);
76     SavingsAccount sa1(1, 58320212, 0.015);
77 
78     //几笔账目
79     sa0.deposit(5, 5000);
80     sa1.deposit(25, 10000);
81     sa0.deposit(45, 5500);
82     sa1.withdraw(60, 4000);
83 
84     //开户后第90天到了银行的计息日,结算所有账户的年息
85     sa0.settle(90);
86     sa1.settle(90);
87 
88     //输出各个账户信息
89     sa0.show();    cout << endl;
90     sa1.show();    cout << endl;
91     return 0;
92 }

下面是用Java改写之后的版本:

  1 package PersonalSavingAccount4;
  2 
  3  class SavingAccount {
  4     private int id;                 //账号
  5     private double balance;         //余额
  6     private double rate;            //存款的年利率
  7     private int lastDate;           //上次变更余额的时期
  8     private double accumulation;     //余额按日累加只和
  9 
 10     //记录一笔账,date为日期,amount为金额,desc为说明
 11     private void record(int date,double amount){
 12         this.accumulation=accumulate(date);
 13         this.lastDate=date;
 14         amount=Math.floor((amount * 100 + 0.5)/100);
 15         this.balance+=amount;
 16         System.out.println(date + "\t#"+id+ " \t"+ amount+"\t" + balance +"\t");
 17 
 18     }
 19 
 20     //获得到指定日期为止的存款金额按日累计值
 21     final private double accumulate(int data){
 22         return accumulation + balance * (data - lastDate);
 23     }
 24 
 25     //构造函数
 26     public  SavingAccount(int date, int id, double rate){
 27         this.id=id;
 28         this.balance=0;
 29         this.rate=rate;
 30         this.lastDate=date;
 31         this.accumulation=0;
 32         System.out.println(date + "\t#"+id+ " is created"+"\t");
 33     }
 34 
 35     public int getId(){
 36 
 37         return this.id;
 38     }
 39 
 40     double getBalance(){
 41 
 42         return this.balance;
 43     }
 44 
 45     double getRate(){
 46 
 47         return this.rate;
 48     }
 49 
 50     //存入现金
 51     void deposit(int date, double amount){
 52 
 53         record(date, amount);
 54     }
 55 
 56     //取出现金
 57     void withdraw(int date, double amount){
 58         if(amount > getBalance())
 59             System.out.println("Error: not enough money");
 60         else
 61             record(date, -amount);
 62 
 63     }
 64 
 65     //结算利息, 每年1月1日调用一次该函数
 66     void settle(int date){
 67         double interest = accumulate(date) * rate / 365;
 68         if(interest !=0)
 69             record(date, interest);
 70         accumulation = 0;
 71 
 72     }
 73 
 74     //显示账户信息
 75     void show(){
 76         System.out.println("#" + id +"\tBalance"+ balance);
 77     }
 78 
 79     public static void main(String[] args){
 80         //建立几个账户
 81         SavingAccount sa0 = new SavingAccount(1,21325302,0.015);
 82         SavingAccount sa1 = new SavingAccount(1,58320212,0.015);
 83 
 84         //几笔账目
 85         sa0.deposit(5,5000);
 86         sa1.deposit(25,10000);
 87         sa0.deposit(45,5500);
 88         sa1.withdraw(60,4000);
 89 
 90         ///开户后第90天到了银行的计息日,结算所有账户的年息
 91         sa0.settle(90);
 92         sa1.settle(90);
 93 
 94         //输出各个账户信息
 95         sa0.show();
 96         sa1.show();
 97     }
 98 
 99 
100 
101 }

C++和Java的比较:

相同点:都运用了类的相关概念,使得代码简洁高效。

不同点:

1、C++在新建一个对象时不需要使用new关键字,而Java必须使用new关键字创建新的对象

2、C++在声明private、public、private类型时可以分区进行,Java则必须依次说明。

3、C++类的成员函数的函数体可以放在类外面写,从而大大减少类的长度,Java则不行

4、C++的const和java中的const区别很大,具体如下:

在C++中:

   1) const对象只能访问const成员函数,而非const对象可以访问任意的成员函数,包括const成员函数。
    2) const对象的成员是不可修改的,然而const对象通过指针维护的对象却是可以修改的。
    3) const成员函数不可以修改对象的数据,不管对象是否具有const性质.它在编译时,以是否修改成员数据为依据,进行检查。
    4) 然而加上mutable修饰符的数据成员,对于任何情况下通过任何手段都可修改,自然此时的const成员函数是可以修改它的。
 
在Java中:
const创建一个指向值的不可变指针,但其自身的值仍然可变。
如果要定义一个常量、让方法不被改写等则需要使用final关键字。 
 
 
 
2.0版本
需求分析:实现银行账户开户、存款、取钱、结算利息,输出余额、并记录每一笔帐及其说明。
C++版本:
 1 //account.h 头文件
 2 #ifndef __ACCOUNT_H__
 3 #define __ACCOUNT_H__
 4 
 5 class SavingsAccount { 
 6 private:
 7     int id;                
 8     double balance;        
 9     double rate;        
10     int lastDate;        
11     double accumulation;    
12     static double total;    
13 
14     
15     void record(int date, double amount);
16     
17     double accumulate(int date) const {
18         return accumulation + balance * (date - lastDate);
19     }
20 public:
21     
22     SavingsAccount(int date, int id, double rate);
23     int getId() const { return id; }
24     double getBalance() const { return balance; }
25     double getRate() const { return rate; }
26     static double getTotal() { return total; }
27 
28     
29     void deposit(int date, double amount);
30     
31     void withdraw(int date, double amount);
32     
33     void settle(int date);
34     
35     void show() const;
36 };
37 
38 #endif //__ACCOUNT_H__
39 
40 
41 
42 //主函数
43 //5_11.cpp
44 #include "account.h"
45 #include <iostream>
46 using namespace std;
47 
48 int main() {
49     //建立几个账户
50     SavingsAccount sa0(1, 21325302, 0.015);
51     SavingsAccount sa1(1, 58320212, 0.015);
52 
53     //几笔账目
54     sa0.deposit(5, 5000);
55     sa1.deposit(25, 10000);
56     sa0.deposit(45, 5500);
57     sa1.withdraw(60, 4000);
58 
59     //开户后第90天到了银行的计息日,结算所有账户的年息
60     sa0.settle(90);
61     sa1.settle(90);
62 
63     //输出各个账户信息
64     sa0.show();    cout << endl;
65     sa1.show();    cout << endl;
66     cout << "Total: " << SavingsAccount::getTotal() << endl;
67     return 0;
68 }

Java版本:

  1 package PersonalSavingAccount5;
  2 
  3  class SavingAccount {//储蓄账户类
  4     private int id;                 //账号
  5     private double balance;         //余额
  6     private double rate;            //存款的年利率
  7     private int lastDate;           //上次变更余额的时期
  8     private double accumulation;     //余额按日累加只和
  9     static double total;            //所有账户的总金额
 10 
 11     //记录一笔账,date为日期,amount为金额,desc为说明
 12     private void record(int date,double amount){
 13         this.accumulation=accumulate(date);
 14         this.lastDate=date;
 15         amount=Math.floor((amount * 100 + 0.5)/100);
 16         this.balance+=amount;
 17         total+=amount;
 18         System.out.println(date + "\t#"+id+ " \t"+ amount+"\t" + balance +"\t");
 19 
 20     }
 21 
 22     //获得到指定日期为止的存款金额按日累计值
 23     final private double accumulate(int data){
 24 
 25         return accumulation + balance * (data - lastDate);
 26     }
 27 
 28     //构造函数
 29     public  SavingAccount(int date, int id, double rate){
 30         this.id=id;
 31         this.balance=0;
 32         this.rate=rate;
 33         this.lastDate=date;
 34         this.accumulation=0;
 35         System.out.println(date + "\t#"+id+ " is created"+"\t");
 36     }
 37 
 38     public int getId(){
 39 
 40         return this.id;
 41     }
 42 
 43     public double getBalance(){
 44 
 45         return this.balance;
 46     }
 47 
 48     public double getRate(){
 49 
 50         return this.rate;
 51     }
 52 
 53     public static double getTotal(){
 54 
 55         return total;
 56     }
 57 
 58     //存入现金
 59     public void deposit(int date, double amount){
 60         record(date, amount);
 61 
 62     }
 63 
 64     //取出现金
 65     public void withdraw(int date, double amount){
 66         if(amount > getBalance())
 67             System.out.println("Error: not enough money");
 68         else
 69             record(date, -amount);
 70 
 71     }
 72 
 73     //结算利息, 每年1月1日调用一次该函数
 74     public void settle(int date){
 75         double interest = accumulate(date) * rate / 365;
 76         if(interest !=0)
 77             record(date, interest);
 78         accumulation = 0;
 79 
 80     }
 81 
 82     //显示账户信息
 83     public void show(){
 84         System.out.println("#" + id +"\tBalance"+ balance);
 85     }
 86 }
 87 
 88 
 89 //main类
 90 package PersonalSavingAccount5;
 91 public class RunAccount {
 92     public static void main(String[] args){
 93         //建立几个账户
 94         SavingAccount sa0 = new SavingAccount(1,21325302,0.015);
 95         SavingAccount sa1 = new SavingAccount(1,58320212,0.015);
 96 
 97         //几笔账目
 98         sa0.deposit(5,5000);
 99         sa1.deposit(25,10000);
100         sa0.deposit(45,5500);
101         sa1.withdraw(60,4000);
102 
103         ///开户后第90天到了银行的计息日,结算所有账户的年息
104         sa0.settle(90);
105         sa1.settle(90);
106 
107         //输出各个账户信息
108         sa0.show();
109         sa1.show();
110         System.out.println("Total: " + SavingAccount.getTotal());
111     }
112 }

C++和Java的比较:

相同点:

都运用了分类书写的思想,C++中把头文件、.cpp文件、和主文件分开写,放在三个文件中,显得更整洁、更清晰;同样,Java中引入了包的概念,可以在其分别创建类,将运行类和一般类分开书写。

不同点:

和1.0版本类似,并无太多改进。

 

3.0版本

需求分析:实现银行账户开户、存款、取钱、结算利息,输出余额、并记录每一笔帐及其说明,新加入日期类,使其计算利息更加准确。

  1 //account.h
  2 #ifndef __ACCOUNT_H__
  3 #define __ACCOUNT_H__
  4 #include "date.h"
  5 #include <string>
  6 
  7 class SavingsAccount { //储蓄账户类
  8 private:
  9     std::string id;        //帐号
 10     double balance;        //余额
 11     double rate;        //存款的年利率
 12     Date lastDate;        //上次变更余额的时期
 13     double accumulation;    //余额按日累加之和
 14     static double total;    //所有账户的总金额
 15 
 16     //记录一笔帐,date为日期,amount为金额,desc为说明
 17     void record(const Date &date, double amount, const std::string &desc);
 18     //报告错误信息
 19     void error(const std::string &msg) const;
 20     //获得到指定日期为止的存款金额按日累积值
 21     double accumulate(const Date& date) const {
 22         return accumulation + balance * date.distance(lastDate);
 23     }
 24 public:
 25     //构造函数
 26     SavingsAccount(const Date &date, const std::string &id, double rate);
 27     const std::string &getId() const { return id; }
 28     double getBalance() const { return balance; }
 29     double getRate() const { return rate; }
 30     static double getTotal() { return total; }
 31 
 32     //存入现金
 33     void deposit(const Date &date, double amount, const std::string &desc);
 34     //取出现金
 35     void withdraw(const Date &date, double amount, const std::string &desc);
 36     //结算利息,每年1月1日调用一次该函数
 37     void settle(const Date &date);
 38     //显示账户信息
 39     void show() const;
 40 };
 41 
 42 #endif //__ACCOUNT_H__
 43 
 44 
 45 //date.h
 46 #ifndef __DATE_H__
 47 #define __DATE_H__
 48 
 49 class Date {    //日期类
 50 private:
 51     int year;        //
 52     int month;        //
 53     int day;        //
 54     int totalDays;    //该日期是从公元元年1月1日开始的第几天
 55 
 56 public:
 57     Date(int year, int month, int day);    //用年、月、日构造日期
 58     int getYear() const { return year; }
 59     int getMonth() const { return month; }
 60     int getDay() const { return day; }
 61     int getMaxDay() const;        //获得当月有多少天
 62     bool isLeapYear() const {    //判断当年是否为闰年
 63         return year % 4 == 0 && year % 100 != 0 || year % 400 == 0;
 64     }
 65     void show() const;            //输出当前日期
 66     //计算两个日期之间差多少天    
 67     int distance(const Date& date) const {
 68         return totalDays - date.totalDays;
 69     }
 70 };
 71 
 72 #endif //__DATE_H__
 73 
 74 
 75 
 76 //6_25.cpp
 77 #include "account.h"
 78 #include <iostream>
 79 using namespace std;
 80 
 81 int main() {
 82     Date date(2008, 11, 1);    //起始日期
 83     //建立几个账户
 84     SavingsAccount accounts[] = {
 85         SavingsAccount(date, "S3755217", 0.015),
 86         SavingsAccount(date, "02342342", 0.015)
 87     };
 88     const int n = sizeof(accounts) / sizeof(SavingsAccount); //账户总数
 89     //11月份的几笔账目
 90     accounts[0].deposit(Date(2008, 11, 5), 5000, "salary");
 91     accounts[1].deposit(Date(2008, 11, 25), 10000, "sell stock 0323");
 92     //12月份的几笔账目
 93     accounts[0].deposit(Date(2008, 12, 5), 5500, "salary");
 94     accounts[1].withdraw(Date(2008, 12, 20), 4000, "buy a laptop");
 95 
 96     //结算所有账户并输出各个账户信息
 97     cout << endl;
 98     for (int i = 0; i < n; i++) {
 99         accounts[i].settle(Date(2009, 1, 1));
100         accounts[i].show();
101         cout << endl;
102     }
103     cout << "Total: " << SavingsAccount::getTotal() << endl;
104     return 0;
105 }

Java版本:

  1 package PersonalSavingAccount6;
  2 
  3 public class SavingAccount {//储蓄账户类
  4     private String id;          //账号
  5     private double balance;     //余额
  6     private double rate;        //存款的年利率
  7     private Date lastDate;      //上次变更余额的时期
  8     private double accumulation;        //余额按日累加之和
  9     private static double total;        //所有账户的总金额
 10 
 11     //构造函数
 12     public SavingAccount(final Date date, final String id, double rate){
 13         this.id=id;
 14         this.rate=rate;
 15         this.lastDate=date;
 16         this.balance=0;
 17         this.accumulation=0;
 18 
 19     }
 20 
 21     public final String getId(){
 22         return this.id;
 23     }
 24 
 25     public double getBalance(){
 26         return this.balance;
 27     }
 28 
 29     public double getRate(){
 30         return this.rate;
 31     }
 32 
 33     public static double getTotal(){
 34         return total;
 35     }
 36 
 37     //记录一笔账,data为日期,amount为金额, desc为说明
 38     private void record(final Date date, double amount, final String desc ){
 39         accumulation=accumulate(date);
 40         this.lastDate=date;
 41         amount=Math.floor((amount*100 + 0.5) / 100);
 42         this.balance+=amount;
 43         total+=amount;
 44         date.show();
 45         System.out.println("\t#" + this.id + "\t" + amount + "\t" + balance + "\t" +desc);
 46     }
 47 
 48     //报告错误信息
 49     private void error(final String msg){
 50         System.out.println("Error(#" + this.id +")" + msg);
 51     }
 52 
 53     //获得指定日期为止的存款金额按日累积值
 54     private double accumulate(final Date date){
 55         return accumulation + balance * date.distance(lastDate);
 56     }
 57 
 58     //存入现金
 59     void deposit(Date date, double amount, String desc){
 60         record(date,amount,desc);
 61     }
 62 
 63     //取出现金
 64     void withdraw(Date date, double amount, String desc){
 65         if(amount > getBalance())
 66             error("Not enough money!");
 67         else
 68             record(date, -amount , desc );
 69     }
 70 
 71     //结算利息,每年1月1日调用一次该函数
 72     void settle(Date date){
 73         double interest = accumulate(date) * rate/date.distance(new Date(date.getYear() - 1, 1, 1));  //计算年息
 74         if(interest != 0)
 75             record(date, interest ,"interest");
 76         accumulation = 0;
 77     }
 78 
 79     //显示账户信息
 80     void show(){
 81         System.out.println(this.id + "\tBalance: " + this.balance);
 82     }
 83 
 84 
 85 
 86 }
 87 
 88 
 89 
 90 //Date类
 91 package PersonalSavingAccount6;
 92 
 93  class Date {
 94     private int year;       //
 95     private int month;      //
 96     private int day;        //
 97     private int totalDays;   //该日期是从公元元年1月1日开始的第几天
 98     private final int DAYS_BEFORE_MONTH[] = {0,31,59,120,151,181,212,243,273,304,334,365,396};
 99 
100     //用年、月、日构造日期
101     public Date(int year, int month, int day){
102         this.year=year;
103         this.month=month;
104         this.day=day;
105         if(day <= 0 || day > getMaxDay()){
106             System.out.println("Invalid date");
107             show();
108             return;
109         }
110         int years = year -1;
111         totalDays = years *365 + year/4 -years / 100 +years /400 + DAYS_BEFORE_MONTH[month - 1] + day;
112         if(isLeapYear() && month >2){
113             totalDays++;
114         }
115 
116     }
117 
118     public int getYear(){
119         return this.year;
120     }
121 
122     public int getMonth(){
123         return this.month;
124     }
125 
126     public int getDay(){
127         return this.day;
128     }
129 
130     //获得当月有多少天
131     public int getMaxDay(){
132         if (isLeapYear() && month==2)
133             return 29;
134         else
135             return DAYS_BEFORE_MONTH[month]-DAYS_BEFORE_MONTH[month-1];
136     }
137 
138     //判断当年是否是闰年
139     boolean isLeapYear(){
140         return year % 4==0 && year % 100 != 0 || year % 400 ==0;
141     }
142 
143     //输出当前日期
144     void show(){
145         System.out.println(getYear()+"-"+getMonth()+"-"+getDay());
146     }
147 
148     //计算两个日期之间差多少天
149     int distance(final Date date){
150         return this.totalDays - date.totalDays;
151     }
152 }
153 
154 
155 //RunAccount类
156 package PersonalSavingAccount6;
157 
158 public class RunAccount {
159     public static void main(String[] args){
160         Date date = new Date(2008, 11, 1); //起始日期
161         //建立几个账户
162         SavingAccount[] accounts;
163         accounts = new SavingAccount[]{
164                 new SavingAccount(date, "S3755217", 0.015),
165                 new SavingAccount(date, "02342342", 0.015)
166         };
167         //final int n = accounts.length; //账户总数
168         //11月份的几笔账目
169         accounts[0].deposit(new Date(2008, 11, 5), 5000, "salary");
170         accounts[1].deposit(new Date(2008, 11, 25), 10000, "sell stock 0323");
171         //12月份的几笔账目
172         accounts[0].deposit(new Date(2008, 12 ,5), 5500, "salary");
173         accounts[1].withdraw(new Date(2008, 12, 20),4000, "buy a laptop");
174 
175         //结算所有账目并输出各个账户信息
176         System.out.println();
177         for (SavingAccount account : accounts) {
178             account.settle(new Date(2009, 1, 1));
179             account.show();
180             System.out.println();
181         }
182         System.out.println("Total:" + SavingAccount.getTotal());
183     }
184 }

相同点:

都选择了新建一个Date类,是得计算利息的方法更加准确。

不同点:

1)可以看出Java自带丰富的类库,可以调用各种方法以方便使用。

如计算数组的长度时,可以直接数组名.length(),调用length方法即可得到数组长度,而C++则需要声明引入文件,如#include<cmath>,才能使用其方法。

2)Java中的数组必须进行声明和初始化才能进行,而且其数组长度是new出来的

3)C++中加入了namespace的概念,在其大括号范围内表示的意思是只在当前文件夹有效,而在Java中,因为有了包的概念,所以说只需要将数据或方法设成private就可以达成同样效果了。

 

4.0版本

需求分析:需求分析:实现银行账户开户、存款、取钱、结算利息,输出余额、并记录每一笔帐及其说明,加入日期类,使其计算利息更加准确,新增信用账户类(继承),新增Accumulator类,账户余额及其明细更加清楚。

 C++版本:(只含信用账户类及计算类)

 1 class CreditAccount : public Account { //信用账户类
 2 private:
 3     Accumulator acc;    //辅助计算利息的累加器
 4     double credit;        //信用额度
 5     double rate;        //欠款的日利率
 6     double fee;            //信用卡年费
 7 
 8     double getDebt() const {    //获得欠款额
 9         double balance = getBalance();
10         return (balance < 0 ? balance : 0);
11     }
12 public:
13     //构造函数
14     CreditAccount(const Date &date, const std::string &id, double credit, double rate, double fee);
15     double getCredit() const { return credit; }
16     double getRate() const { return rate; }
17     double getFee() const { return fee; }
18     double getAvailableCredit() const {    //获得可用信用
19         if (getBalance() < 0) 
20             return credit + getBalance();
21         else
22             return credit;
23     }
24     //存入现金
25     void deposit(const Date &date, double amount, const std::string &desc);
26     //取出现金
27     void withdraw(const Date &date, double amount, const std::string &desc);
28     //结算利息和年费,每月1日调用一次该函数
29     void settle(const Date &date);
30 
31     void show() const;
32 };
33 
34 
35 
36 //accumulator.h
37 #ifndef __ACCUMULATOR_H__
38 #define __ACCUMULATOR_H__
39 #include "date.h"
40 
41 class Accumulator {    //将某个数值按日累加
42 private:
43     Date lastDate;    //上次变更数值的时期
44     double value;    //数值的当前值
45     double sum;        //数值按日累加之和
46 public:
47     //构造函数,date为开始累加的日期,value为初始值
48     Accumulator(const Date &date, double value)
49         : lastDate(date), value(value), sum(0) { }
50 
51     //获得到日期date的累加结果
52     double getSum(const Date &date) const {
53         return sum + value * date.distance(lastDate);
54     }
55 
56     //在date将数值变更为value
57     void change(const Date &date, double value) {
58         sum = getSum(date);
59         lastDate = date;
60         this->value = value;
61     }
62 
63     //初始化,将日期变为date,数值变为value,累加器清零
64     void reset(const Date &date, double value) {
65         lastDate = date;
66         this->value = value;
67         sum = 0;
68     }
69 };
70 
71 #endif //__ACCUMULATOR_H__

Java版本:(只含信用账户类及计算类)

  1 package PersonalSavingAccount7;
  2 
  3  class CreditAccount extends Account{//信用账户类
  4     //private
  5     private Accumulator acc;    //辅助计算利息的累加器
  6     private double credit;      //信用额度
  7     private double rate;        //欠款的日利率
  8     private double fee;         //信用卡年费
  9 
 10     private double getDebt(){       //获得欠款额
 11         double balance= getBalance();
 12         return (balance < 0 ? balance : 0);
 13     }
 14 
 15     //public
 16      // 构造函数
 17      public CreditAccount(final Date date, final String id, double credit, double rate, double fee){
 18             super(date,id);
 19             this.credit= credit;
 20             this.rate= rate;
 21             this.fee= fee;
 22             this.acc= new Accumulator(date,0);
 23      }
 24      public double getCredit() {
 25 
 26         return credit;
 27     }
 28 
 29      public double getRate() {
 30 
 31         return rate;
 32     }
 33      public double getFee() {
 34 
 35         return fee;
 36     }
 37      public double getAvailableCredit()  {    //获得可用信用
 38          if (getBalance() < 0)
 39              return credit + getBalance();
 40          else
 41              return credit;
 42      }
 43      //存入现金
 44      public void deposit(final Date date, double amount, final String desc){
 45         record(date, amount, desc);
 46         acc.change(date, getDebt());
 47      }
 48      //取出现金
 49      public void withdraw(final Date date, double amount, final String desc){
 50         if(amount - getBalance() >credit){
 51             error(" not enough credit!");
 52         }else{
 53             record(date, -amount, desc);
 54             acc.change(date, getDebt());
 55         }
 56      }
 57      //结算利息和年费,每月1日调用一次该函数
 58      public void settle(final Date date){
 59         double interest = acc.getSum(date) * rate;
 60         if(interest != 0)
 61             record(date, interest, "interest");
 62         if(date.getMonth() == 1)
 63             record(date, -fee, "annual fee");
 64         acc.reset(date, getDebt());
 65      }
 66 
 67 
 68      public void show() {
 69         super.show();
 70         System.out.println("\tAvailable credit" + getAvailableCredit());
 71      }
 72 
 73  }
 74 
 75 
 76 
 77 package PersonalSavingAccount7;
 78 
 79  class Accumulator {
 80     private Date lastDate;  //上次变更数值的时期
 81     private double value;   //数值的当前值
 82     private double sum;     //数值按日累加之和
 83 
 84     //构造函数,date为开始累加的日期,value为初始值
 85     public Accumulator(final Date date, double value){
 86         this.lastDate=date;
 87         this.value=value;
 88         this.sum=0;
 89     }
 90 
 91     //获得到日期date的累加结果
 92     double getSum(final Date date){
 93 
 94         return sum + value * date.distance(lastDate);
 95     }
 96 
 97     //在date将数值变更为value
 98     void change(final Date date, double value){
 99         this.sum= getSum(date);
100         this.lastDate= date;
101         this.value =value;
102     }
103 
104     //初始化,将日期变为date, 数值变为value ,累加器清零
105     void reset(final Date date, double value){
106         this.lastDate= date;
107         this.value= value;
108         this.sum=0;
109     }
110 
111 
112 }

不同点:

1)Java和C++的继承方式有差异,前者需要使用extends 关键字进行继承声明,而后者的继承方式是class 子类 : (访问权限) 父类1,(访问权限)父类2;值得一提的是,Java中只允许单继承,即一个子类只能有一个父类,而C++则允许有多个父类。

2)Java中子类的构造方法中,可以使用super方法调用父类的构造方法,初始化父类中相应的数据成员,无论显式使用super还是隐式,父类的构造方法都会被调用;C++中则是直接调用父类的构造方法。

3)在使用构造方法时,若形参名和声明的数据变量名相同时(如id),C++中可以用id(id)表示初始化,而Java则必须用this.id=id进行赋值。

 

5.0

需求分析:需求分析:实现银行账户开户、存款、取钱、结算利息,输出余额、并记录每一笔帐及其说明,加入日期类,使其计算利息更加准确,增加信用账户类(继承),增加Accumulator类,账户余额及其明细更加清楚,新增菜单功能,用户可以根据自己的需求选择相应的功能。

C++版本:

  1 //此处就只显示变动较大的account类和含菜单功能的代码
  2 
  3 //account.h
  4 #ifndef __ACCOUNT_H__
  5 #define __ACCOUNT_H__
  6 #include "date.h"
  7 #include "accumulator.h"
  8 #include <string>
  9 
 10 class Account { //账户类
 11 private:
 12     std::string id;    //帐号
 13     double balance;    //余额
 14     static double total; //所有账户的总金额
 15 protected:
 16     //供派生类调用的构造函数,id为账户
 17     Account(const Date &date, const std::string &id);
 18     //记录一笔帐,date为日期,amount为金额,desc为说明
 19     void record(const Date &date, double amount, const std::string &desc);
 20     //报告错误信息
 21     void error(const std::string &msg) const;
 22 public:
 23     const std::string &getId() const { return id; }
 24     double getBalance() const { return balance; }
 25     static double getTotal() { return total; }
 26     //存入现金,date为日期,amount为金额,desc为款项说明
 27     virtual void deposit(const Date &date, double amount, const std::string &desc) = 0;
 28     //取出现金,date为日期,amount为金额,desc为款项说明
 29     virtual void withdraw(const Date &date, double amount, const std::string &desc) = 0;
 30     //结算(计算利息、年费等),每月结算一次,date为结算日期
 31     virtual void settle(const Date &date) = 0;
 32     //显示账户信息
 33     virtual void show() const;
 34 };
 35 
 36 class SavingsAccount : public Account { //储蓄账户类
 37 private:
 38     Accumulator acc;    //辅助计算利息的累加器
 39     double rate;        //存款的年利率
 40 public:
 41     //构造函数
 42     SavingsAccount(const Date &date, const std::string &id, double rate);
 43     double getRate() const { return rate; }
 44     virtual void deposit(const Date &date, double amount, const std::string &desc);
 45     virtual void withdraw(const Date &date, double amount, const std::string &desc);
 46     virtual void settle(const Date &date);
 47 };
 48 
 49 class CreditAccount : public Account { //信用账户类
 50 private:
 51     Accumulator acc;    //辅助计算利息的累加器
 52     double credit;        //信用额度
 53     double rate;        //欠款的日利率
 54     double fee;            //信用卡年费
 55 
 56     double getDebt() const {    //获得欠款额
 57         double balance = getBalance();
 58         return (balance < 0 ? balance : 0);
 59     }
 60 public:
 61     //构造函数
 62     CreditAccount(const Date &date, const std::string &id, double credit, double rate, double fee);
 63     double getCredit() const { return credit; }
 64     double getRate() const { return rate; }
 65     double getFee() const { return fee; }
 66     double getAvailableCredit() const {    //获得可用信用
 67         if (getBalance() < 0) 
 68             return credit + getBalance();
 69         else
 70             return credit;
 71     }
 72     virtual void deposit(const Date &date, double amount, const std::string &desc);
 73     virtual void withdraw(const Date &date, double amount, const std::string &desc);
 74     virtual void settle(const Date &date);
 75     virtual void show() const;
 76 };
 77 
 78 #endif //__ACCOUNT_H__
 79 
 80 
 81 //8_8.cpp
 82 #include "account.h"
 83 #include <iostream>
 84 using namespace std;
 85 
 86 int main() {
 87     Date date(2008, 11, 1);    //起始日期
 88     //建立几个账户
 89     SavingsAccount sa1(date, "S3755217", 0.015);
 90     SavingsAccount sa2(date, "02342342", 0.015);
 91     CreditAccount ca(date, "C5392394", 10000, 0.0005, 50);
 92     Account *accounts[] = { &sa1, &sa2, &ca };
 93     const int n = sizeof(accounts) / sizeof(Account*);    //账户总数
 94 
 95     cout << "(d)deposit (w)withdraw (s)show (c)change day (n)next month (e)exit" << endl;
 96     char cmd;
 97     do {
 98         //显示日期和总金额
 99         date.show();
100         cout << "\tTotal: " << Account::getTotal() << "\tcommand> ";
101 
102         int index, day;
103         double amount;
104         string desc;
105 
106         cin >> cmd;
107         switch (cmd) {
108         case \'d\':    //存入现金
109             cin >> index >> amount;
110             getline(cin, desc);
111             accounts[index]->deposit(date, amount, desc);
112             break;
113         case \'w\':    //取出现金
114             cin >> index >> amount;
115             getline(cin, desc);
116             accounts[index]->withdraw(date, amount, desc);
117             break;
118         case \'s\':    //查询各账户信息
119             for (int i = 0; i < n; i++) {
120                 cout << "[" << i << "] ";
121                 accounts[i]->show();
122                 cout << endl;
123             }
124             break;
125         case \'c\':    //改变日期
126             cin >> day;
127             if (day < date.getDay())
128                 cout << "You cannot specify a previous day";
129             else if (day > date.getMaxDay())
130                 cout << "Invalid day";
131             else
132                 date = Date(date.getYear(), date.getMonth(), day);
133             break;
134         case \'n\':    //进入下个月
135             if (date.getMonth() == 12)
136                 date = Date(date.getYear() + 1, 1, 1);
137             else
138                 date = Date(date.getYear(), date.getMonth() + 1, 1);
139             for (int i = 0; i < n; i++)
140                 accounts[i]->settle(date);
141             break;
142         }
143     } while (cmd != \'e\');
144     return 0;
145 }

Java版本:

  1 package PersonalSavingAccount8;
  2 
  3 abstract class Account {
  4     //private
  5     private  String id;         //账号
  6     private double balance;     //余额
  7     private static double total;    //所有账户的总金额
  8 
  9     //protected
 10     //供派生类调用的构造函数, id为账户
 11     protected Account(final Date date, String id){
 12         this.id= id;
 13         this.balance= 0;
 14         date.show();
 15         System.out.println("\t#" + id + "created");
 16     }
 17 
 18     //记录一笔账,date为日期,amount为金额,desc为说明
 19     protected void record(final Date date, double amount, final String desc ){
 20         amount =Math.floor((amount *100 +0.5)/100);     //保留小数点后两位
 21         this.balance+= amount;
 22         total+= amount;
 23         date.show();
 24         System.out.println("\t#" + id +"\t" +amount +"\t" +balance +"\t" +desc);
 25     }
 26 
 27     //报告错误信息
 28     protected void error(final String msg){
 29 
 30         System.out.println("Error(#" +id +")" +msg);
 31     }
 32 
 33     //public
 34     public String getId(){
 35 
 36         return id;
 37     }
 38 
 39     public double getBalance(){
 40 
 41         return balance;
 42     }
 43 
 44     public static double getTotal(){
 45 
 46         return total;
 47     }
 48 
 49     //抽象函数
 50     //存入现金,date为日期,amount为金额,desc为款项说明
 51     public abstract void deposit(final Date date, double amount, final String desc);
 52 
 53     //取出现金,date为日期,amount为金额,desc为款项说明
 54     public abstract void withdraw(final Date date, double amount, final String desc );
 55 
 56     //结算(计算利息、年费等),每月结算一次,date为结算日期
 57     public abstract void settle(final Date date);
 58 
 59     //显示账户信息
 60     public abstract void show();
 61 
 62 
 63 }
 64 
 65 
 66 package PersonalSavingAccount8;
 67 
 68 import java.util.Scanner;
 69 
 70 class RunAccount {
 71     public static void main(String[] args) {
 72         Date date = new Date(2008, 11, 1);
 73         //建立几个账户
 74         SavingAccount sa1 = new SavingAccount(date, "S3755217", 0.015);
 75         SavingAccount sa2 = new SavingAccount(date, "02342342", 0.015);
 76         CreditAccount ca = new CreditAccount(date, "C5392394", 0.0005, 50);
 77         Account[] accounts = {sa1, sa2, ca};
 78         int n = accounts.length;    //账户总数
 79 
 80         System.out.println("(d)deposit (w)withdraw (s)show (c)change day (n)next month (e)exit");
 81         Scanner cmd = new Scanner(System.in);
 82         do {
 83             //显示日期和总金额
 84             date.show();
 85             System.out.println("\tTotal: " + Account.getTotal() + "\tcommand");
 86 
 87             Scanner index, day, amount, desc;
 88 
 89             index = new Scanner(System.in);
 90             day = new Scanner(System.in);
 91             amount = new Scanner(System.in);
 92             desc = new Scanner(System.in);
 93 
 94             String contents = cmd.next();
 95             switch (contents) {
 96                 case "d":  //存入现金
 97                     System.out.println("您现在正在进行的是存入现金操作:");
 98                     System.out.println("请输入你想操作账户的编码:(0~2):");
 99                     int index1 = index.nextInt();
100                     System.out.println("请输入金额:");
101                     float amount1 = amount.nextFloat();
102                     System.out.println("请作出相应的说明:");
103                     String desc1 = desc.next();
104                     accounts[index1].deposit(date, amount1, desc1);
105                     break;
106 
107                 case "w":  //取出现金
108                     System.out.println("您现在正在进行的是取出现金操作:");
109                     System.out.println("请输入你想操作账户的编码:(0~2):");
110                     int index2 = index.nextInt();
111                     System.out.println("请输入金额:");
112                     float amount2 = amount.nextFloat();
113                     System.out.println("请作出相应的说明:");
114                     String desc2 = desc.next();
115                     accounts[index2].withdraw(date, amount2, desc2);
116                     break;
117 
118                 case "s":  //查询各账户信息
119                     System.out.println("您现在正在进行的是查询各账户信息操作:");
120                     for (int i = 0; i < n; i++) {
121                         System.out.print("[" + i + "]");
122                         accounts[i].show();
123                         System.out.println();
124 
125                     }
126                     break;
127 
128                 case "c":  //改变日期
129                     System.out.println("您现在正在进行的是改变日期操作:");
130                        int day1 = day.nextInt();
131                        if(day1 <date.getDay()){
132                            System.out.println("You can\'t specify a previous day!");
133                        }else if(day1 > date.getMaxDay()) {
134                            System.out.println("Invalid day!");
135                        }else {
136                            date = new Date(date.getYear(), date.getMonth(),day1);
137                        }
138                     break;
139 
140                 case "n":  //进入下个月
141                     System.out.println("进入了下个月:");
142                     if (date.getMonth() == 12) {
143                         date = new Date(date.getYear() + 1, 1, 1);
144                     } else {
145                         date = new Date(date.getYear(), date.getMonth() + 1, 1);
146                     }
147                     for (Account account : accounts) {
148                         account.settle(date);
149                     }
150                     break;
151 
152             }
153         } while (! cmd.equals("e"));
154     }
155 
156 }
157 
158 //夹杂了点私货,给菜单使用进行了一点说明

不同点:

1)Java和C++的抽象类、抽象方法使用不同;Java在使用抽象方法时,其类名和方法名前面必须加上关键字abstract,C++在抽象函数名字前加上virtual关键字即可。

2)在比较字符串的值是否相等时,例如s1="abc",s2="abc", C++中可以直接用==判定二者的值是否相等,而Java则得使用.equals() 的API来判别。

分类:

技术点:

相关文章: