问题:
编写一个程序,完成在银行的取款和存款操作。在定义银行类时,若取款大于余额则作为异常处理
MyException.java
package bank;
public class MyException extends Exception{
public MyException(String msg) {
super(msg);
}
}
bankSystem.java
package bank;
import java.util.Scanner;
public class bankSystem {
private int balance = 0;//余额
private int deposit;//存款额
private int withdraw;//取款额
public int getBalance() {
return this.balance;
}
//取钱
public void doWithdraw(int withdraw){
try {
if(balance < withdraw) {
MyException me = new MyException("余额不足!");
throw me;
}
balance-=withdraw;
}
catch(MyException me){
System.out.println(me.toString());
}
}
//存钱
public void doDeposit(int deposit) {
balance += deposit;
}
//查询余额
public String toStringBalance() {
return "您的余额为:" + this.getBalance();
}
public void doBusiness() {
Scanner input = new Scanner(System.in);
System.out.println("请输入您要办理的业务:\n1.存钱\n2.取钱\n3.查询余额");
int choice = input.nextInt();
switch(choice)
{
case 1:
System.out.println("请输入存钱金额:");
int depositMoney = input.nextInt();
doDeposit(depositMoney);
break;
case 2:
System.out.println("请输入取钱金额:");
int withdrawMoney = input.nextInt();
doWithdraw(withdrawMoney);
break;
case 3:
System.out.println(toStringBalance());
break;
}
}
}
test.java
package bank;
public class test {
public static void main(String[] args) {
// TODO Auto-generated method stub
bankSystem bank = new bankSystem();
while(true)
{
bank.doBusiness();
System.out.println();
}
}
}
运行结果