Java教程

C++改Java——个人银行账户管理

本文主要是介绍C++改Java——个人银行账户管理,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

第4章:类

    class SavingsAccount { //储蓄账户类
        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 final double accumulate(int date) {
            return accumulation + balance * (date - lastDate);
        }

        //构造函数
        public SavingsAccount(int date, int id, double rate) {
            this.id=id;
            balance=0;
            this.rate=rate;
            lastDate=date;
            accumulation=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.print("#"+id+"\tBalance: "+balance);
        }
    }

    public class javafour {
        public static void main(String[] args) {
            //建立几个账户
            SavingsAccount sa0 = new SavingsAccount(1,21325302,0.015);
            SavingsAccount sa1 = new SavingsAccount(1, 58320212, 0.015);

            //几笔账目
            sa0.deposit(5, 5000);
            sa1.deposit(25, 10000);
            sa0.deposit(45, 5500);
            sa1.withdraw(60, 4000);

            //开户后第90天到了银行的计息日,结算所有账户的年息
            sa0.settle(90);
            sa1.settle(90);

            //输出各个账户信息
            sa0.show();
            System.out.println();
            sa1.show();
            System.out.println();
        }
    }


第5章: 增添静态属性与方法

class SavingsAccount2{
    private int id;				//账号
    private double balance;		//余额
    private double rate;		//存款的年利率
    private int lastDate;		//上次变更余额的时期
    private double accumulation;	//余额按日累加之和
    private static double total = 0;

    //SavingsAccount类相关成员函数的实现
    public SavingsAccount2(int date, int id, double rate){
        this.id=id;
        balance=0;
        this.rate=rate;
        lastDate=date;
        accumulation=0;
        System.out.println(date+"\t#"+id+" is created");
    }

    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 final double accumulate(int date) {
        return accumulation + balance * (date - lastDate);
    }


    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);
        }
    }

    public void settle(int date) {
        double interest = accumulate(date) * rate / 365;	//计算年息
        if (interest != 0){
            record(date, interest);
        }
        accumulation = 0;
    }

    public final void show()  {
        System.out.print("#"+id+"\tBalance: "+balance);
    }

    public static double getTotal(){
        return total;
    }
}
public class javafiveaccount{
    public static void main(String[] args) {
        //建立几个账户
        SavingsAccount2 sa0 = new SavingsAccount2(1, 21325302, 0.015);
        SavingsAccount2 sa1 = new SavingsAccount2(1, 58320212, 0.015);

        //几笔账目
        sa0.deposit(5, 5000);
        sa1.deposit(25, 10000);
        sa0.deposit(45, 5500);
        sa1.withdraw(60, 4000);

        //开户后第90天到了银行的计息日,结算所有账户的年息
        sa0.settle(90);
        sa1.settle(90);

        //输出各个账户信息
        sa0.show();
        System.out.println();
        sa1.show();
        System.out.println();
        System.out.print("Total: "+ SavingsAccount2.getTotal());
    }
}


第6章:增添字符串、对象数组

class Date {
    private int year;
    private int month;
    private int day;
    private static int totalDays = 0;
    public 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 int getYear(){return year;}

    public int getMonth(){return month;}

    public int getDay(){return day;}

    public final boolean isLeapYear(){
        return year % 4 == 0 && year % 100 != 0 || year % 400 == 0;
    }

    public double distance(Date a){
            return totalDays;
    }
}


class SavingsAccount3{
    private String id;				//账号
    private double balance;		//余额
    private double rate;		//存款的年利率
    private Date lastDate;		//上次变更余额的时期
    private double accumulation;	//余额按日累加之和
    private static double total = 0;

    //SavingsAccount类相关成员函数的实现
    public SavingsAccount3(final Date date, final String id, double rate) {
        this.id=id;
        balance=0;
        this.rate=rate;
        lastDate=date;
        accumulation=0;
        date.show();
        System.out.println("\t#"+id+" is created");
    }

    public void record(final Date date, double amount, final 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 final double accumulate(Date date) {
        return accumulation + balance * (date.distance(date));
    }

    public String getId() {
        return id;
    }

    public double getBalance() {
        return balance;
    }

    public double getRate() {
        return rate;
    }

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

    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()) {
            error("not enough money");
        }
        else {
            record(date, -amount, desc);
        }
    }

    public void settle(final Date date) {
        double interest = accumulate(date) * rate	//计算年息
                / date.distance(new Date(date.getYear() - 1, 1, 1));
        if (interest != 0) {
            record(date, interest, "interest");
        }
        accumulation = 0;
    }

    public final void show(){
        System.out.print(id+"\tBalance: "+balance);
    }

    public static double getTotal(){
        return total;
    }
}
public class javasix{
    public static void main(String[] args) {
             Date date = new Date(2008, 11, 1);	//起始日期
            //建立几个账户
            SavingsAccount3[] accounts= {
                    new SavingsAccount3(date, "S3755217", 0.015),
                    new SavingsAccount3(date, "02342342", 0.015)
            };
	        final int n = accounts.length; ///  size(SavingsAccount3); //账户总数
            //11月份的几笔账目
            accounts[0].deposit(new Date(2008, 11, 5), 5000, "salary");
            accounts[1].deposit(new Date(2008, 11, 25), 10000, "sell stock 0323");
            //12月份的几笔账目
            accounts[0].deposit(new Date(2008, 12, 5), 5500, "salary");
            accounts[1].withdraw(new Date(2008, 12, 20), 4000, "buy a laptop");

            //结算所有账户并输出各个账户信息
            System.out.println();
            for (int i = 0; i < n; i++) {
                accounts[i].settle(new Date(2009, 1, 1));
                accounts[i].show();
                System.out.println();
            }
            System.out.println("Total: "+ SavingsAccount3.getTotal());
    }
}


第7章:继承与派生,抽象出父类,增添子类

class Date2{
    private int year;
    private int month;
    private int day;
    private static int totalDays = 0;
    public final int[] DAYS_BEFORE_MONTH= { 0,31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 };

    public Date2(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 int getYear(){return year;}

    public int getMonth(){return month;}

    public int getDay(){return day;}

    public final boolean isLeapYear(){
        return year % 4 == 0 && year % 100 != 0 || year % 400 == 0;
    }
    public final int distance(final Date2 date){
        return (totalDays -date.totalDays);
    }
}

class Accumulator {	//将某个数值按日累加
    private Date2 lastDate;	//上次变更数值的时期
    private double value;	//数值的当前值
    private double sum;		//数值按日累加之和


    //构造函数,date为开始累加的日期,value为初始值
    public Accumulator(final  Date2 date, double value) {
        lastDate=date;
        this.value=value;
        sum=0;
    }

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

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

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



//Account类的实现
class Account {
    private String id;                //账号
    private double balance;        //余额
    private static double total = 0;

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


    protected void record(final Date2 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  final void error(final String msg) {
        System.out.println("Error(#" + id + "): " + msg);
    }

    public void show() {
        System.out.print(id + "\tBalance: " + balance);
    }

    public final String getld(){return id;}

    public double getBalance() {
        return balance;
    }

    public static double getTotal() {
        return total;
    }

}


//SavingsAccount类相关成员函数的实现
class SavingsAccount4 extends Account{
    private double rate;
    private Accumulator acc;

    public SavingsAccount4(final Date2 date,final String id,double rate) {
         super(date, id);
         //若一个父类只要有一个带参数的构造方法,
        // 那么在写其子类的构造方法时必须先通过super调用父类的构造方法才能完成子类的构造方法而且super只能写在子类构造方法体内的第一行。
         this.rate=rate;
         acc=new Accumulator(date, 0);
     }

    public double getRate(){return rate;}

    public void deposit(final Date2 date, double amount, final String desc) {
        record(date, amount, desc);
        acc.change(date, getBalance());
    }

    public void withdraw(final Date2 date, double amount, final String desc) {
        if (amount > getBalance()) {
            error("not enough money");
        } else {
            record(date, -amount, desc);
            acc.change(date, getBalance());
        }
    }

    public void settle(final Date2 date) {
        double interest = acc.getSum(date) * rate    //计算年息
                / date.distance(new Date2(date.getYear() - 1, 1, 1));
        if (interest != 0)
            record(date, interest, "interest");
        acc.reset(date, getBalance());
    }
}


//CreditAccount类相关成员函数的实现
class  CreditAccount extends Account{
    private double credit;
    private double rate;
    private double fee;
    private Accumulator acc;

    private final double getDebt(){
        double balance = getBalance();
        return (balance < 0 ? balance : 0);
    }

    public CreditAccount(final Date2 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 final double getCredit() { return credit; }

    public final double getRate() { return rate; }

    public final double getFee() { return fee; }

    public final double getAvailableCredit(){	//获得可用信用
        if (getBalance() < 0)
            return credit + getBalance();
        else
            return credit;
    }

    public void deposit(final Date2 date, double amount,final String desc) {
        record(date, amount, desc);
        acc.change(date, getDebt());
    }

    public void withdraw(final Date2 date, double amount,final String desc) {
        if (amount - getBalance() > credit) {
            error("not enough credit");
        } else {
            record(date, -amount, desc);
            acc.change(date, getDebt());
        }
    }

    public void settle(final Date2 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 final void show(){
        super.show ();
        System.out.print("\tAvailable credit:" + getAvailableCredit());
    }
}


public class javaseven {
    public static void main(String[] args) {
        Date2 date= new Date2(2008, 11, 1);	//起始日期
        //建立几个账户
        SavingsAccount4 sa1=new SavingsAccount4(date, "S3755217", 0.015);
        SavingsAccount4 sa2=new SavingsAccount4(date, "02342342", 0.015);
        CreditAccount ca=new CreditAccount(date, "C5392394", 10000, 0.0005, 50);
        //11月份的几笔账目
        sa1.deposit(new Date2(2008, 11, 5), 5000, "salary");
        ca.withdraw(new Date2(2008, 11, 15), 2000, "buy a cell");
        sa2.deposit(new Date2(2008, 11, 25), 10000, "sell stock 0323");
        //结算信用卡
        ca.settle(new Date2(2008, 12, 1));
        //12月份的几笔账目
        ca.deposit(new Date2(2008, 12, 1), 2016, "repay the credit");
        sa1.deposit(new Date2(2008, 12, 5), 5500, "salary");
        //结算所有账户
        sa1.settle(new Date2(2009, 1, 1));
        sa2.settle(new Date2(2009, 1, 1));
        ca.settle(new Date2(2009, 1, 1));
        //输出各个账户信息
        System.out.println();
        sa1.show();
        System.out.println();
        sa2.show();
        System.out.println();
        ca.show();
        System.out.println();
        System.out.println("Total: "+Account.getTotal());
    }
}


第8章:多态特性

import java.util.Scanner;

class Date3{	//日期类
    private int year;		//年
    private int month;		//月
    private int day;		//日
    private int totalDays;	//该日期是从公元元年1月1日开始的第几天
    public final int[] DAYS_BEFORE_MONTH= { 0,31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 };

    public Date3(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++;
    }

    public final int getYear() { return year; }

    public final int getMonth() { return month; }

    public final int getDay(){ return day; }

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

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

    public final void show(){//输出当前日期
        System.out.println( getYear() +"-" +getMonth()+ "-" +getDay());
    }

    //计算两个日期之间差多少天
    public final int operator(final Date3 date){
        return totalDays - date.totalDays;
    }
}


class Accumulator2 {	//将某个数值按日累加
    private Date3 lastDate;	//上次变更数值的时期
    private double value;	//数值的当前值
    private double sum;		//数值按日累加之和

    //构造函数,date为开始累加的日期,value为初始值
    public Accumulator2(final  Date3 date, double value) {
        lastDate=date;
        this.value=value;
        sum=0;
    }

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

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

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


abstract class Account2 { //账户类
    private String id;	//帐号
    private double balance;	//余额
    private static double total=0; //所有账户的总金额

    //供派生类调用的构造函数,id为账户
    protected Account2(final Date3 date, final String id){
        this.id=id;
        balance=0;
        date.show();
        System.out.println("\t#" +id + " created" );
    }
    //记录一笔帐,date为日期,amount为金额,desc为说明
    protected void record(final Date3 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 final void error(final String  msg){
        System.out.println("Error(#" + id + "): " + msg);
    }


    public final String getId() { return id; }

    public final double getBalance(){ return balance; }

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




class SavingsAccount5 extends Account2 { //储蓄账户类
    private Accumulator2 acc;    //辅助计算利息的累加器
    private double rate;        //存款的年利率

    //构造函数
    public SavingsAccount5(final Date3 date, final String id, double rate) {
        super(date, id);
        this.rate = rate;
        acc = new Accumulator2(date, 0);
    }


    public final double getRate() {
        return rate;
    }

    public void deposit(final Date3 date, double amount, final String desc) {
        record(date, amount, desc);
        acc.change(date, getBalance());
    }

    public void withdraw(final Date3 date, double amount, final String desc) {
        if (amount > getBalance()) {
            error("not enough money");
        } else {
            record(date, -amount, desc);
            acc.change(date, getBalance());
        }
    }

    public void settle(final Date3 date) {
        if (date.getMonth() == 1) {    //每年的一月计算一次利息
            double interest = acc.getSum(date) * rate
                    / (date.operator(new Date3(date.getYear() - 1, 1, 1))  );
            if (interest != 0)
                record(date, interest, "interest");
            acc.reset(date, getBalance());
        }
    }
}





class CreditAccount2 extends Account2 { //信用账户类

    private Accumulator2 acc;	//辅助计算利息的累加器
    private  double credit;		//信用额度
    private  double rate;		//欠款的日利率
    private  double fee;			//信用卡年费


    private  final double getDebt() {	//获得欠款额
            double balance = getBalance();
            return (balance < 0 ? balance : 0);
        }

        //构造函数
    public CreditAccount2(final Date3 date, final String id, double credit, double rate, double fee){
        super(date,id);
        this.credit=credit;
        this.rate=rate;
        this.fee=fee;
        acc=new Accumulator2(date, 0);
    }


    public final double getCredit()  { return credit; }
    public final double getRate() { return rate; }
    public final double getFee() { return fee; }
    public final double getAvailableCredit() {	//获得可用信用
         if (getBalance() < 0)
        return credit + getBalance();
        else
        return credit;
        }

    public  void deposit(final Date3 date, double amount,  final String desc){
        record(date, amount, desc);
        acc.change(date, getDebt());
    }


    public  void withdraw(final Date3 date, double amount,  final String desc){
        if (amount - getBalance() > credit) {
            error("not enough credit");
        } else {
            record(date, -amount, desc);
            acc.change(date, getDebt());
        }
    }

    public  void settle(final Date3 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.print("\tAvailable credit:" + getAvailableCredit());
    }
}

public class javaeight {
    public static void main(String[] args) {
        Date3 date=new Date3(2008, 11, 1);	//起始日期
        //建立几个账户
        SavingsAccount5 sa1=new SavingsAccount5(date, "S3755217", 0.015);
        SavingsAccount5 sa2=new SavingsAccount5(date, "02342342", 0.015);
        CreditAccount2 ca=new CreditAccount2(date, "C5392394", 10000, 0.0005, 50);
        Account2[] accounts={sa1, sa2, ca};
	    final int n; // sizeof(Account*);	//账户总数
        n = accounts.length;

        System.out.println("(d)deposit (w)withdraw (s)show (c)change day (n)next month (e)exit" );
        char cmd;
        do {
            //显示日期和总金额
            date.show();
            System.out.println("\tTotal: " +Account2.getTotal() + "\tcommand> ");

            int index, day;
            double amount;
            String desc;

            Scanner input=new Scanner(System.in);
            String c=input.next();
            cmd=c.charAt(0);
            switch (cmd) {
                case 'd':	//存入现金
                    index=input.nextInt();
                    amount=input.nextDouble();
                    desc=input.next();
                    accounts[index].deposit(date, amount, desc);
                    break;
                case 'w':	//取出现金
                    index=input.nextInt();
                    amount=input.nextDouble();
                    desc=input.next();
                    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();
                    }
                    break;
                case 'c':	//改变日期
                    day=input.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 Date3(date.getYear(), date.getMonth(), day);
                    break;
                case 'n':	//进入下个月
                    if (date.getMonth() == 12)
                        date = new Date3(date.getYear() + 1, 1, 1);
                    else
                        date = new Date3(date.getYear(), date.getMonth() + 1, 1);
                    for (int i = 0; i < n; i++)
                        accounts[i].settle(date);
                    break;
            }
        } while (cmd != 'e');
    }
}


第9章:使用容器代替数组

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
import java.util.*;

class Date4 {	//日期类
    private int year;		//年
    private int month;		//月
    private int day;		//日
    private int totalDays;	//该日期是从公元元年1月1日开始的第几天
    public final int[] DAYS_BEFORE_MONTH= { 0,31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 };

    public Date4(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++;
    }

    public final int getYear() { return year; }
    public final int getMonth(){ return month; }
    public final int getDay() { return day; }

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

    public final boolean isLeapYear() {	//判断当年是否为闰年
        return year % 4 == 0 && year % 100 != 0 || year % 400 == 0;
    }
    public final void show() {//输出当前日期
        System.out.println( getYear() +"-" +getMonth()+ "-" +getDay());
    }
    //计算两个日期之间差多少天
    public final int operator(final Date4 date){
        return totalDays - date.totalDays;
    }
}


class Accumulator3 {	//将某个数值按日累加
    private Date4 lastDate;	//上次变更数值的时期
    private double value;	//数值的当前值
    private double sum;		//数值按日累加之和

    //构造函数,date为开始累加的日期,value为初始值
    public Accumulator3(final  Date4 date, double value) {
        lastDate=date;
        this.value=value;
        sum=0;
    }

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

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

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





abstract class Account3 { //账户类
    private String id;	//帐号
    private double balance;	//余额
    private static double total; //所有账户的总金额

    //供派生类调用的构造函数,id为账户
    protected Account3(final Date4 date,final String id){
        this.id=id;
        balance=0;
        date.show();
        System.out.println("\t#" +id + " created" );
    }
    //记录一笔帐,date为日期,amount为金额,desc为说明
    protected void record(final Date4 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 final void error(final String msg){
        System.out.println("Error(#" + id + "): " + msg);
    }

    public final String getId() { return id; }

    public final double getBalance(){ return balance; }

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



class SavingsAccount6 extends Account3 { //储蓄账户类
    private Accumulator3 acc;	//辅助计算利息的累加器
    private double rate;		//存款的年利率

        //构造函数
    public SavingsAccount6(final Date4 date,final String id, double rate){
        super(date, id);
        this.rate = rate;
        acc = new Accumulator3(date, 0);
    }

    public final double getRate() { return rate; }

    public void deposit(final Date4 date, double amount,final String desc){
        record(date, amount, desc);
        acc.change(date, getBalance());
    }

    public void withdraw(final Date4 date, double amount,final String desc){
        if (amount > getBalance()) {
            error("not enough money");
        } else {
            record(date, -amount, desc);
            acc.change(date, getBalance());
        }
    }

    public void settle(final Date4 date){
        if (date.getMonth() == 1) {    //每年的一月计算一次利息
            double interest = acc.getSum(date) * rate
                    / (date.operator(new Date4(date.getYear() - 1, 1, 1))  );
            if (interest != 0)
                record(date, interest, "interest");
            acc.reset(date, getBalance());
        }
    }
}


class CreditAccount6 extends Account3 { //信用账户类
    private Accumulator3 acc;	//辅助计算利息的累加器
    private double credit;		//信用额度
    private double rate;		//欠款的日利率
    private double fee;			//信用卡年费

    private final double getDebt(){	//获得欠款额
        double balance = getBalance();
        return (balance < 0 ? balance : 0);
    }

        //构造函数
    public CreditAccount6(final Date4 date,final String id, double credit, double rate, double fee){
        super(date,id);
        this.credit=credit;
        this.rate=rate;
        this.fee=fee;
        acc=new Accumulator3(date, 0);
    }

    public final double getCredit() { return credit; }

    public final double getRate() { return rate; }

    public final double getFee()  { return fee; }

    public final double getAvailableCredit(){	//获得可用信用
        if (getBalance() < 0)
        return credit + getBalance();
        else
        return credit;
    }

    public  void deposit(final Date4 date, double amount,final String desc) {
        record(date, amount, desc);
        acc.change(date, getDebt());
    }

    public  void withdraw(final Date4 date, double amount,final String desc){
        if (amount - getBalance() > credit) {
            error("not enough credit");
        } else {
            record(date, -amount, desc);
            acc.change(date, getDebt());
        }
    }

    public  void settle(final Date4 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.print("\tAvailable credit:" + getAvailableCredit());
    }
}


public class javanine {
    public static void main(String[] args) {
        Date4 date=new Date4(2008, 11, 1);	//起始日期
        //Array<Account *> accounts(0); 创建账户数组,元素个数为0
        ArrayList<Account3> accounts = new ArrayList<>();

        System.out.println("(a)add account (d)deposit (w)withdraw (s)show (c)change day (n)next month (e)exit" );

        char cmd;
        do {
            //显示日期和总金额
            date.show();
            System.out.println("\tTotal: " +Account3.getTotal() + "\tcommand> ");

            char type;
            int index, day;
            double amount, credit, rate, fee;
            String id, desc;
            Account3 account;

            Scanner input=new Scanner(System.in);
            String c=input.next();
            cmd=c.charAt(0);
            switch (cmd) {
                case 'a':	//增加账户
                    Scanner inputt=new Scanner(System.in);
                    String t=inputt.next();
                    type=t.charAt(0);
                    id=input.next();
                    if (type == 's') {
                        rate=input.nextDouble();
                        account = new SavingsAccount6(date, id, rate);
                    } else {
                        credit=input.nextDouble();
                        rate=input.nextDouble();
                        fee=input.nextDouble();
                        account = new CreditAccount6(date, id, credit, rate, fee);
                    }
                    //accounts.resize(accounts.length + 1);
                    accounts.add(account);
                    break;
                case 'd':	//存入现金
                    index=input.nextInt();
                    amount=input.nextDouble();
                    desc=input.next();
                    accounts.get(index).deposit(date, amount, desc);
                    break;
                case 'w':	//取出现金
                    index=input.nextInt();
                    amount=input.nextDouble();
                    desc=input.next();
                    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':	//改变日期
                    day=input.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 Date4(date.getYear(), date.getMonth(), day);
                    break;
                case 'n':	//进入下个月
                    if (date.getMonth() == 12)
                        date =new Date4(date.getYear() + 1, 1, 1);
                    else
                        date =new Date4(date.getYear(), date.getMonth() + 1, 1);
                    for (int i = 0; i < accounts.size(); i++)
                        accounts.get(i).settle(date);
                    break;
            }
        } while (cmd != 'e');

        for (int i = 0; i < accounts.size(); i++)
            accounts.remove(i);

    }
}


 

这篇关于C++改Java——个人银行账户管理的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!