7-5 设计BankAccount类

设计一个BankAccount类,这个类包括:

(1)一个int型的balance表时账户余额。

(2)一个无参构造方法,将账户余额初始化为0。

(3)一个带一个参数的构造方法,将账户余额初始化为该输入的参数。

(4)一个getBlance()方法,返回账户余额。

(5)一个withdraw()方法:带一个amount参数,并从账户余额中提取amount指定的款额。

(6)一个deposit()方法:带一个amount参数,并将amount指定的款额存储到该银行账户上。

提供main函数,构造一个账户对象,并对其进行存取款操作。

其中操作类型类型为1表示存款,2表示取款,每次操作后都打印余额

输入格式:

账户余额
操作个数
操作类型 操作金额

输出格式:

每次操作后的余额

输入样例:

在这里给出一组输入。例如:

0
4
1 100
1 200
2 100
2 100

输出样例:

在这里给出相应的输出。例如:

100
300
200
100
import java.util.Scanner;
class BankAccount
{
    int balance;
    public BankAccount(){
        this.balance= 0;
}
    public BankAccount(int t){
        this.balance= t;
}
    public int getBalance(){
        return this.balance;
}
    public void withdraw(int x){
        if(this.balance>=x)
            this.balance -= x;
        else
            ;
}
    public void deposit(int x) {
        this.balance += x;
    }
    public void print()
    {
        System.out.println(balance);
    }
}
public class Main
{
    public static void main(String[] args) {
        Scanner sc= new Scanner(System.in);
         // 输入初始余额
        int t=sc.nextInt();
        // 创建账户对象
        BankAccount p = new BankAccount(t);
        int cycle= sc.nextInt();
        for(int i=0;i<cycle;i++)
        {
            if(sc.nextInt()==1)
                p.deposit(sc.nextInt());
            else
                p.withdraw(sc.nextInt());
             // 打印余额
            p.print();
        }
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值