【优化】自定义抛出throw 对象练习

2023-05-17,,

 package ltb6w;
import java.util.*; public class Bank { private boolean bool=true;
private String select;
private String select2;
private double balance=0.0; //余额
private double inputbalance=0.0; private Scanner sc=new Scanner(System.in); public Bank() { System.out.println("请输入存款额度:"); } @SuppressWarnings("serial")
class NotSufficientFunds extends Exception { //自定义异常类 private String insufficient; NotSufficientFunds(String s ) { insufficient=s;
} public String getMessage() { return insufficient; } } public void deposite() throws Exception{//存款操作 try { inputbalance=sc.nextInt();// 容易出异常的地方 }catch (InputMismatchException e) { System.out.println("请输入数字:"); this.bool=false;
} if(inputbalance<0) { throw new NotSufficientFunds("存款不能是负数"); //抛出自定义异常
} this.balance=inputbalance+balance; System.out.println("存款总额:"+balance);
} public void withdrawa() throws Exception{//取款操作 System.out.println("请输入取款数:"); this.balance=balance-sc.nextInt(); if (balance<0) { //激发异常类 throw new NotSufficientFunds("余额已经是负数了"); } System.out.println("余额:"+this.getbalawal());
} public double getbalawal() { //获取余额操作 return balance;
} public void getBank() { System.out.println("是否继续存款:是or否"); select=sc.next(); // 容易出异常的地方 if("否".equals(select)) { while (true) { System.out.println("看仔细了!!!是否还继续取款:是or否"); try {
select2=sc.next(); // 容易出异常的地方 }catch (InputMismatchException e) { System.out.println("不要输入(是or否)之外无关的数据,从来,再来。"+e.getMessage()); } if("是".equals(select2)) { try {
withdrawa(); break;
} catch (Exception e) { e.printStackTrace();
} }else if ("否".equals(select2)){ System.out.println("不管你选不选否都当做退出。["+select2+"]"); break;
} } bool=false; System.out.println("已经成功退出"); }else if("是".equals(select)) {
System.out.println("继续输入金额,come on baby!");
}
} public static void main(String[] args) throws Exception { Bank b=new Bank(); while (b.bool) { b.deposite();
b.getBank(); } } }

【优化】自定义抛出throw 对象练习的相关教程结束。

《【优化】自定义抛出throw 对象练习.doc》

下载本文的Word格式文档,以方便收藏与打印。