Java异常处理Exception——银行余额不足实例

问题:

编写一个程序,完成在银行的取款和存款操作。在定义银行类时,若取款大于余额则作为异常处理

 

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

}

运行结果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值