zoukankan      html  css  js  c++  java
  • 2.建立exception包,建立Bank类,类中有变量double balance表示存款,Bank类的构造方法能增加存款,Bank类中有取款的发方法withDrawal(double dAmount),当取款的数额大于存款时,抛出InsufficientFundsException,取款数额为负数,抛出NagativeFundsException,如new Bank(100),表示存入银行1

    //Bank类
    package d0923;

    public class Bank {
    private double balance;

    Bank(double a) {
    	balance += a;
    }
    
    void withDrawal(double dAmount) throws InsufficientFundsException, NagativeFundsException  {
    	if(dAmount<0)		
    		throw new InsufficientFundsException(dAmount);
    	if(dAmount>balance)
    		throw new NagativeFundsException();
    	System.out.println("取款:"+dAmount);
    	this.balance-=dAmount;
    }
    

    }

    ///InsufficientFundsException
    package d0923;

    public class InsufficientFundsException extends Exception {
    InsufficientFundsException(double i)
    {
    System.out.println("发生错误:"+"取款额"+i+"为负数。");
    }
    }

    ///NagativeFundsException
    package d0923;

    public class NagativeFundsException extends Exception {
    NagativeFundsException()
    {
    System.out.println("超出余额:");
    }
    }

    package d0923;

    public class NagativeFundsException extends Exception {
    NagativeFundsException()
    {
    System.out.println("超出余额:");
    }
    }

    //测试主类

    package d0923;

    public class TestBank {

    public static void main(String[] args)  {
    	Bank b=new Bank(100);
    	try{
    		b.withDrawal(-15);
    	}
    	catch(InsufficientFundsException e)
    	{
    		e.printStackTrace();
    	}
    	catch(NagativeFundsException e)
    	{
    		e.printStackTrace();
    	}
    	
    	try{
    		b.withDrawal(150);
    	}
    	catch(InsufficientFundsException | NagativeFundsException e)
    	{
    		e.printStackTrace();
    	}
    
    
    }
    

    }
    //运行结果

    发生错误:取款额-15.0为负数。 ///withdrawal调用的构造函数
    d0923.InsufficientFundsException
    at d0923.Bank.withDrawal(Bank.java:12) /// printStack
    at d0923.TestBank.main(TestBank.java:8)
    超出余额:
    d0923.NagativeFundsException
    at d0923.Bank.withDrawal(Bank.java:14)
    at d0923.TestBank.main(TestBank.java:20)

  • 相关阅读:
    unity, trail renderer gone black on iOS
    sql date时间加减几天几小时
    mysql sql获取上条插入id,update影响行数
    cmd获取系统时间
    js/jquery 实时监听输入框值变化的完美方案:oninput & onpropertychange
    javascript 动态改变onclick事件
    限制input输入类型(多种方法实现)
    在VMware Workstation11虚拟机上安装黑苹果
    mysql存储过程procedure
    我常用的在线取色器
  • 原文地址:https://www.cnblogs.com/nicebaby/p/5904942.html
Copyright © 2011-2022 走看看