设计一个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();
}
}
}