Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package BankAccount;
- class InvalidBalanceException extends Exception {
- public InvalidBalanceException(String msg) {
- super(msg);
- }
- }
- class Account {
- double balance;
- Account(double balance) throws InvalidBalanceException {
- credit(balance);
- }
- public void debit(double amount) throws InvalidBalanceException {
- if((balance - amount) < 0) {
- throw new InvalidBalanceException("The account balance can’t be less than zero");
- } else {
- balance -= amount;
- }
- }
- public void credit (double amount) throws InvalidBalanceException {
- if(amount < 0) {
- throw new InvalidBalanceException("The account balance can’t be less than zero");
- } else {
- balance += amount;
- }
- }
- }
- public class Bank {
- public static void main(String[] args) {
- Account account;
- try {
- account = new Account(1000);
- account.credit(500);
- System.out.println(account.balance);
- account.debit(500);
- System.out.println(account.balance);
- account.debit(2000);
- System.out.println(account.balance);
- } catch (InvalidBalanceException e) {
- System.out.println(e.getMessage());
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement