public class Account {
private double balance;
public Account(double balance){
super();
this.balance=balance;
}
public Account(){
super();
}
public void withdraw(double money) throws NotFullBalanceException{
//取款
if(money<=balance){
balance -= money;
}
else{
throw new NotFullBalanceException("余额不足");
}
}
public void despoit(double money){
//存款
balance += money;
}
public double getBalance() {
return balance; }
}
zzzz
public class NotFullBalanceException extends Exception{
public NotFullBalanceException(){
}
public NotFullBalanceException(String msg){
super(msg);
}
}
zzzz
import java.util.InputMismatchException;
import java.util.Scanner;
public class TestAccount {
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
Account account = new Account(10000);
while(true){
System.out.println("****当前账户余额:"+ account.getBalance()+"****");
System.out.println("1.存钱 2.取钱 0.退出");
System.out.print("请选择(1,2,0):");
String cmd = scn.next().trim();
if("0".equals(cmd)){ //避免空指针异常,将常量写在前面
System.out.println("bye..."); break;
}
else if("1".equals(cmd)){//1.存钱
System.out.print("请输入金额:");
try{
double money = scn.nextDouble(); account.despoit(money); }
catch(InputMismatchException e){
System.out.println("输入有误...");
scn.next(); }
}
else if("2".equals(cmd)){//2.取钱
System.out.print("请输入金额:");
try { double money = scn.nextDouble();
account.withdraw(money);
}
catch(InputMismatchException e){
System.out.println("输入有误..."); scn.next();
}
catch (NotFullBalanceException e) {
1 System.out.println(e.getMessage());
}
}else{
System.out.println("没有这个命令...");
}
}
}
}