Java小练习

编写一个帐户类实现银行帐户的概念,创建帐户类的对象,完成存款与取款等操作。

             定义一个银行帐户类BankAccount实现银行帐户的概念,在BankAccount类中定义两个变量:"帐号"(account_number) "存款余额" (leftmoney),再定义四个方法:"存款"(savemoney)"取款" (getmoney) "查询余额"(getleftmoney)、构造方法(BankAccount)

最后,在main()方法中创建一个BankAccount类的对象ba,假设ba的账号为:123456,初始的存款余额为500元。首先向该账户存入1000元,再取出2000元。源代码如下:

                      public classBankAccount {

 

                                private int account_number;

                                private double leftmoney;

                                  public double getleftmoney() {//查询余额

                                           return this.leftmoney;

                                }

                                    public void savemoney(double money) {//存款

                                           leftmoney +=money;

System.out.println("存入"+money+"元后,您的余额为:"+leftmoney);

                                         }

                           public void getmoney(doublemoney) {//取款

                             if(leftmoney>=money){

                                       leftmoney-=money;

                                   System.out.println("取出"+money+"元后,您的余额为:"+leftmoney);

                                }

                          else {

                      System.out.println("您的余额不足"+money+"元,"+"最多只能取"+leftmoney+"元");

                    }

             }

                   public BankAccount(intnumber,double money) {//构造方法,用来初始化变量

                        this.account_number = number;

                        this.leftmoney = money;

                  }

                public static void main(String args[]) { 

                   BankAccount ba = new BankAccount(123456,500);

                   ba.savemoney(1000);

                   ba.getmoney(2000);

                }

}

运行结果如下:

  

Java小练习_第1张图片

你可能感兴趣的:(Java小练习)