自定义抛出throw 对象练习

2023-05-17,,

package ltb6w;
import java.util.*; public class Bank { 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{//存款操作 inputbalance=sc.nextInt(); 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 static void main(String[] args) { Bank b=new Bank(); while (true) { try {
b.deposite();
} catch (Exception e) { e.printStackTrace();
} System.out.println("是否继续存款:是or否"); try {
b.select=b.sc.next(); // 容易出异常的地方 }catch (InputMismatchException e) { System.out.println("不要输入(是or否)之外无关的存款数据,从来,再来。"); continue; } if("否".equals(b.select)) { while (true) { System.out.println("看仔细了!!!是否还继续取款:是or否"); try {
b.select2=b.sc.next(); // 容易出异常的地方 }catch (InputMismatchException e) { System.out.println("不要输入(是or否)之外无关的数据,从来,再来。"); continue; } if("是".equals(b.select2)) { try {
b.withdrawa(); break;
} catch (Exception e) { e.printStackTrace();
} }else if ("否".equals(b.select2)){ System.out.println("不管你选不选否都当做退出。["+b.select2+"]"); break;
} } System.out.println("已经成功退出"); break; }else if("是".equals(b.select)) {
System.out.println("继续输入金额,come on baby!");
} } } }

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

《自定义抛出throw 对象练习.doc》

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