个人银行系统的c++代码转化成Java代码
4.cpp
package cjr;
public class bank {
private int id; //账号
private double balance; //余额
private double rate; //存款的年利率
private int lastDate; //上次变更余额的时期
private double accumulation; //余额按日累加之和
//记录一笔帐,date为日期,amount为金额,desc为说明
private void record(int date, double amount)
{
accumulation = accumulate(date);
lastDate = date;
amount = Math.floor((amount * 100 + 0.5)) / 100; //保留小数点后两位
balance += amount;
System.out.println(date + "\t#" + id + "\t" + amount + "\t" + balance);
}
//获得到指定日期为止的存款金额按日累积值
private double accumulate(int date)
{
return accumulation + balance * (date - lastDate);
}
//构造函数
public bank(int date, int id, double rate)
{
this.lastDate = date;
this.id = id;
this.rate = rate;
this.accumulation = 0;
this.balance = 0;
System.out.println(date + "\t#" + id + " is created");
}
public int getId() { return id; }
public double getBalance() { return balance; }
public double getRate() { return rate; }
//存入现金
public void deposit(int date, double amount)
{
record(date, amount);
}
//取出现金
public void withdraw(int date, double amount)
{
if (amount > getBalance())
System.out.println("Error: not enough money");
else
record(date, -amount);
}
//结算利息,每年1月1日调用一次该函数
public void settle(int date)
{
double interest = accumulate(date) * rate / 365; //计算年息
if (interest != 0)
record(date, interest);
accumulation = 0;
}
//显示账户信息
public void show()
{
System.out.println("#" + id + "\tBalance: " + balance);
}
}
(1)去掉namespace改成包(bagpack)的形式
(2)private,public等在Java里面需要单独写在每一个成员前面。
(3)方法的内容要紧紧跟着方法声明后面。和c++不一样。c++可以将函数体写在类外,java不允许。
(4)用到了this,使用this.成员表示当前对象的成员.Java里的构造函数没有id(id)这种写法,大多是this.id=id。
(5)Java里没有const。const和final的用法也不一样。(1)final在java中定义常量,可作用于基本类型或者类类型,若是作用于类类型,则此类类型不能作为父类被继承,也就是说它的下面不能有子类,这样的类叫做原子类。 C++中的const定义常量,(2)Java中的final如果是对于基本类型,那和C++ const是一样的
但是如果是对对象而言,不同了 (3)final表示这个句柄是不可改变的
final Object obj=(Object)new String("a");
obj=(Object)new String("hello");//是非法的
//但是依然可以调用obj的方法。
((String)obj).length() //是合法的
((String)obj).length()是合法的 。而C++如果一个对象被定义成const,就不能调用对象的方法。除非这个方法被定义成const。
(6)Java里是不用写什么math.h等头文件的,类库里都有。比如取整:Math.floor() 。
(7)c++ 里面建立类的对象可以直接:类名 对象名(参数),而Java里面需要:类名 对象名 = new 类名(参数)。
5.cpp
package bank_5;
public class bank_5 {
private int id; //账号
private double balance; //余额
private double rate; //存款的年利率
private int lastDate; //上次变更余额的时期
private double accumulation; //余额按日累加之和
private static double total = 0; //所有账户的总金额
//记录一笔帐,date为日期,amount为金额,desc为说明
private void record(int date, double amount)
{
accumulation = accumulate(date);
lastDate = date;
amount = Math.floor((amount * 100 + 0.5)) / 100; //保留小数点后两位
balance += amount;
total += amount;
System.out.println(date + "\t#" + id + "\t" + amount + "\t" + balance);
}
//获得到指定日期为止的存款金额按日累积值
private double accumulate(int date)
{
return accumulation + balance * (date - lastDate);
}
//构造函数
public bank_5(int date, int id, double rate)
{
this.lastDate = date;
this.id = id;
this.rate = rate;
this.accumulation = 0;
this.balance = 0;
System.out.println(date + "\t#" + id + " is created");
}
public int getId() { return id; }
public double getBalance() { return balance; }
public double getRate() { return rate; }
public static double getTotal() { return total; }
//存入现金
public void deposit(int date, double amount)
{
record(date, amount);
}
//取出现金
public void withdraw(int date, double amount)
{
if (amount > getBalance())
System.out.println("Error: not enough money");
else
record(date, -amount);
}
//结算利息,每年1月1日调用一次该函数
public void settle(int date)
{
double interest = accumulate(date) * rate / 365; //计算年息
if (interest != 0)
record(date, interest);
accumulation = 0;
}
//显示账户信息
public void show()
{
System.out.println("#" + id + "\tBalance: " + balance);
}
}
5和差不多,最后输出了一个total.private static double total = 0; //所有账户的总金额
,用System.out.printf("Total: "+bank_5.getTotal());输出
6.cpp
package banksix;
public class Date {
private int year,month,day,totalDays;//该日期是从公元元年1月1日开始的第几天
private final int[] DAYS_BEFORE_MONTH={0,31,59,90,120,151,181,212,243,273,304,334,365};
public Date(int year,int month,int day){
this.year=year;
this.month=month;
this.day=day;
if(day<=0||day>getMaxDay()){
System.out.print("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++;
}
public final int getMaxDay() {
if(isLeapYear() && month==2) return 29;
else return DAYS_BEFORE_MONTH[month]-DAYS_BEFORE_MONTH[month-1];
}
public final void show() {
System.out.print(getYear()+"-"+getMonth()+"-"+getDay());
}
public final int getYear() {return year;}
public final int getMonth() {return month;}
public final int getDay() {return day;}
public final boolean isLeapYear() {
return year%4==0&&year%100!=0||year%400==0;
}
public final int distance(final Date date) {
return totalDays-date.totalDays;
}
}
package banksix;
public class banksix {
private String id; //账号
private double balance; //余额
private double rate; //存款的年利率
private Date lastDate; //上次变更余额的时期
private double accumulation; //余额按日累加之和
private static double total = 0; //所有账户的总金额
//记录一笔帐,date为日期,amount为金额,desc为说明
private void record(Date date, double amount, String desc)
{
accumulation = accumulate(date);
lastDate = date;
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);
}
//获得到指定日期为止的存款金额按日累积值
private double accumulate(Date date)
{
return accumulation + balance * date.distance(lastDate);
}
//构造函数
public banksix(Date date, String id, double rate)
{
this.lastDate = date;
this.id = id;
this.rate = rate;
this.accumulation = 0;
this.balance = 0;
System.out.println(date + "\t#" + id + " is created");
}
public String getId() { return id; }
public double getBalance() { return balance; }
public double getRate() { return rate; }
public static double getTotal() { return total; }
//存入现金
public void deposit(final Date date, double amount,final String desc)
{
record(date, amount, desc);
}
//取出现金
public void withdraw(final Date date, double amount,final String desc)
{
if (amount > getBalance()) {
System.out.println("Error: not enough money");
} else {
record(date, -amount, desc);
}
}
//结算利息,每年1月1日调用一次该函数
public void settle(Date date)
{
double interest = accumulate(date) * rate / 365; //计算年息
if (interest != 0)
record(date, interest, "interest");
accumulation = 0;
}
//显示账户信息
public void show()
{
System.out.println("#" + id + "\tBalance: " + balance);
}
}
1)再5之上又增加了Date类,将他们放在同一个包中,声明为public,可见。相应的lastdate的属性也要改。
2)Java里是不允许全局变量的,因为这会破坏封装性。
3)创建一个新对象只能用new.在主函数中申明数组格式为banksix []accounts= { new banksix(date, "S3755217", 0.015), new banksix(date, "02342342", 0.015) };
4)Java里的异常退出exit(1)需要调用System.exit(1)。
5)++中的sizeof()函数用来计算对象所占内存空间大小,在java里没有。length()方法返回数组长度,实现的功能相同
7.cpp
Date类与6一样这里不写
//父类
package bankseven;
public class Account {
private String id; //帐号
private double balance; //余额
private static double total = 0; //所有账户的总金额
//供派生类调用的构造函数,id为账户
protected Account(final Date date, final String id)
{
this. id= id;
balance=0;
date.show();
System.out.println("\t#" + id + " created");
}
//记录一笔帐,date为日期,amount为金额,desc为说明
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 );
}
//报告错误信息
protected void error(final String msg)
{
System.out.println("Error(#" + id + "):" + msg);
}
public final String getId() { return id; }
public double getBalance() { return balance; }
public static double getTotal() { return total; }
//显示账户信息
public void show()
{
System.out.print(id + "\tBalance: " + balance);//这里不用println
}
}
//子类
package bankseven;
public class CreditAccount extends Account{
private Accumulator acc; //辅助计算利息的累加器
private double credit; //信用额度
private double rate; //欠款的日利率
private double fee; //信用卡年费
private double getDebt() { //获得欠款额
double balance = getBalance();
return (balance < 0 ? balance : 0);
}
//构造函数
public 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;
acc = new Accumulator(date, 0);
}
public double getCredit() { return credit; }
public double getRate() { return rate; }
public double getFee() { return fee; }
public double getAvailableCredit() { //获得可用信用
if (getBalance() < 0)
return credit + getBalance();
else
return credit;
}
//存入现金
public void deposit(final Date date, double amount,final String desc)
{
record(date, amount, desc);
acc.change(date, getDebt());
}
//取出现金
public 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日调用一次该函数
public 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());
}
public void show()
{
super.show();
System.out.println( "\tAvailable credit:" + getAvailableCredit());
}
}
//子类
package bankseven;
public class SavingsAccount extends Account {
private Accumulator acc; //辅助计算利息的累加器
private double rate; //存款的年利率
//构造函数
public SavingsAccount(final Date date,final String id, double rate)
{
super(date,id);
this.rate = rate;
acc=new Accumulator(date,0);
}
public double getRate() { return rate; }
//存入现金
public void deposit(final Date date, double amount,final String desc)
{
record(date, amount, desc);
acc.change(date, getBalance());
}
//取出现金
public 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日调用一次该函数
public void settle(final Date date)
{
double interest = acc.getSum(date) * rate / date.distance(new Date(date.getYear() - 1, 1, 1)); //计算年息
if (interest != 0)
record(date, interest, "interest");
acc.reset(date, getBalance());
}
}
(1)java中类的继承用的是extends关键字,而非C++里的class SavingsAccount:public Account{};而且java没有C++里的继承类型
(2) 由于CreditAccount中的show()函数显示的与父类不尽相同,在调用父类show(),之后还要将额外的信息输出。
(3)使用super关键字,在调用父类同名的方法时。如上述show()函数的调用。在子类构造方法中需要首先用super(Date,String)去初始化继承自父类那部分的域变量。
(4)由于两类账户计息对象和周期不同,但都需要将某个数值按日累加,所以选择建立新类Accumulator。在调用Accumulator对象时注意使用new。acc=new Accumulator(date,0);
(5)不能将main()方法中的3个账户放在一个对象数组中进行操作.
8.cpp
package bankeight;
import java.text.DecimalFormat;
abstract public class Account {
private String id; //帐号
private double balance; //余额
private static double total = 0; //所有账户的总金额
//供派生类调用的构造函数,id为账户
protected Account(final Date date, final String id)
{
this.id=id;
balance=0;
date.show();
System.out.println("\t#" + id + " created");
}
//记录一笔帐,date为日期,amount为金额,desc为说明
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" + df.format(balance) + "\t" + desc );
}
//报告错误信息
protected void error(final String msg)
{
System.out.println("Error(#" + id + "):" + msg);
}
static DecimalFormat df = new DecimalFormat("0.0");
public final String getId() { return id; }
public double getBalance() { return balance; }
public static double getTotal() { return total; }
//存入现金,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);
//显示账户信息
public void show(){
System.out.print(id + "\tBalance: " + df.format(balance));
}
}
package bankeight;
import java.io.IOException;//则是输入的专用库,每种类型的输入还不一样
import java.text.DecimalFormat;//可以控制输出小数点
import java.util.*;
public class bankeight {
public static void main(String[] args) throws IOException {
Date date = new Date(2008, 11, 1); //起始日期
//建立几个账户
SavingsAccount sa1 = new SavingsAccount(date, "S3755217", 0.015);
SavingsAccount sa2 = new SavingsAccount(date, "02342342", 0.015);
CreditAccount ca = new CreditAccount(date, "C5392394", 10000, 0.0005, 50);
Account accounts[] = { sa1, sa2, ca };
final int n = accounts.length; //账户总数
System.out.println("(d)deposit (w)withdraw (s)show (c)change day (n)next month (e)exit");
char cmd;
Scanner in=new Scanner(System.in); //使用Scanner类定义对象
int index, day;
double amount;
String desc;
DecimalFormat df = new DecimalFormat("0.0");
do {
//显示日期和总金额
date.show();
System.out.print("\tTotal: " + df.format(Account.getTotal()) + "\tcommand> ");
cmd = (char)System.in.read();
switch (cmd) {
case 'd': //存入现金
index = in.nextInt();
amount = in.nextDouble();
desc = in.nextLine();
accounts[index].deposit(date, amount, desc);
break;
case 'w': //取出现金
index = in.nextInt();
amount = in.nextDouble();
desc = in.nextLine();
accounts[index].withdraw(date, amount, desc);
break;
case 's': //查询各账户信息
for (int i = 0; i < n; i++) {
System.out.print("[" + i + "] ");
accounts[i].show();
System.out.println();
if(i<(n-1)) {System.in.read();}
}
break;
case 'c': //改变日期
day = in.nextInt();
if (day < date.getDay())
System.out.print("You cannot specify a previous day");
else if (day > date.getMaxDay())
System.out.print("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 < n; i++) {
accounts[i].settle(date);
if(i<(n-1)) {System.in.read();}
}
break;
}
} while (cmd != 'e');
in.close();
}
}
(1)在JAVA中没有C++中虚函数的virtual关键字,取而代之的是父类中的抽象方法,同C++一样,抽象父类都是使用abstract关键字,不过在Java中,子类实现父类方法时就相当于完成了C++中虚函数的功能。
(2)DecimalFormat是NumberFormat的一个具体子类,用于格式化十进制数字。DecimalFormat包含一个模式和一组符号.
(3)JAVA中没有getline(cin,string)来读入输入的一行命令,java中用`
Scanner in=new Scanner(System.in); //使用Scanner类定义对象。
通过 Scanner 类的 next() 与 nextLine() 方法获取输入的字符串,在读取前我们一般需要 使用 hasNext 与 hasNextLine 判断是否还有输入的数据。如果要输入 int 或 float 类型的数据,在 Scanner 类中也有支持,但是在输入之前最好先使用 hasNextXxx() 方法进行验证,再使用 nextXxx() 来读取
(4) IOException是输入或输出异常(即写读异常)。如果 你用的throws IOException 那么可以不写try catch语句。
(5)java中没有运算符重载,直接