unsplash-image-6AQY7pO1lS0.jpg

Java - Exception Handling and File I/O

Exception Handling and File Input/Output Banking System - Java


This is a banking system program written in Java to add bank accounts, modify them and perform their monthly calculations; and adds file input and file output. Each account requires the account type, account number, account holder’s name, phone number, email, opening balance, fees for a checking account, minimum balance and interest rate for savings account.

This program uses custom exceptions and exception handling with try catch blocks to validate the user input, there is a class for each custom exception that extends the “Exception” class that is part of “java.lang”. The main functions of this program runs with an Array List to store Objects of the type “BankAccount” as defined by the class “BankAccount” which implements the interface “BankSimulator”. There are two different types of accounts, savings and checking, these are two different classes that extend the bank account class. Each account has an account holder that is an object of the class “Person”. The “Bank” class houses the array list and implements all the methods of the other classes to populate the array. Finally the main method houses the menu and calls on the “Bank” class to make it all work.

A video demonstrating the output and the code is shown below:

Source Code

Main Method
Person
Bank Account
Account Types
Bank
Exceptions
Exported from Notepad++
1 // Name: Mostapha Abdelaziz 2 // Class: CST8132 #303 3 // 4 // Assessment: Lab 8 5 // Description: Class for the main method 6 7 package lab8; 8 9 import java.util.Scanner; 10 11 /** 12 * This class is for the main method. 13 * 14 * @author Mostapha Abdelaziz 15 * @version 1.1 16 * @since 1.8 17 * @see Bank 18 */ 19 public class Lab8 { 20 /** 21 * Main method to call and run the code. 22 * 23 * @param String[] 24 * @throws Exception 25 */ 26 // main method 27 public static void main(String[] args) { 28 Scanner input = new Scanner(System.in); 29 String menu = "q"; 30 Bank bank = new Bank(input); 31 32 //loop condition 33 Boolean loop = true; 34 // welcome message 35 System.out.println("======= Welcome to the Banking Simulation Program =======\n"); 36 37 // loop to loop through program until quitting 38 do { 39 // loop to throw and catch any exceptions 40 do { 41 // menu output for choices 42 System.out.print("a: Add new account \n" + "u: Update an account\n" + "d: Display an account\n" 43 + "p: Print all accounts\n" + "m: Run monthly update\n" + "r: Read from text file\n" + 44 "q: Quit\n" + "\n" 45 + "Enter your option: "); 46 47 // try the input and catch any errors 48 try { 49 menu = input.nextLine(); 50 // if it a valid choice, set loop condition to exit loop 51 if (menu.equalsIgnoreCase("a") || menu.equalsIgnoreCase("u") || menu.equalsIgnoreCase("d") 52 || menu.equalsIgnoreCase("p") || menu.equalsIgnoreCase("r") 53 || menu.equalsIgnoreCase("q") || menu.equalsIgnoreCase("m")) { 54 loop = false; 55 } else { 56 // else throw exception 57 System.out.println("\n"); 58 throw new WrongMenuException(); 59 } 60 } catch (WrongMenuException e) { 61 // print error and exception 62 System.out.println(e+ "\n"); 63 } 64 65 } while (loop == true); 66 // switch for each option 67 switch (menu.toLowerCase()) { 68 case "a": 69 System.out.println(); 70 bank.addAccount(); 71 System.out.println(); 72 input.nextLine(); 73 break; 74 case "u": 75 System.out.println(); 76 bank.updateAccount(); 77 System.out.println(); 78 input.nextLine(); 79 break; 80 case "d": 81 System.out.println(); 82 System.out.println(bank.displayAccount()); 83 System.out.println(); 84 input.nextLine(); 85 break; 86 case "p": 87 System.out.println(); 88 bank.printAccountDetails(); 89 System.out.println(); 90 break; 91 case "m": 92 System.out.println(); 93 bank.monthlyUpdate(); 94 System.out.println("\n"); 95 break; 96 case "r": 97 System.out.println(); 98 bank.readFromFile(); 99 break; 100 } 101 102 } while (!menu.equalsIgnoreCase("q")); 103 104 // quit message 105 System.out.println("\nQuit: Successfully exited the program"); 106 107 // close scanner 108 input.close(); 109 } 110 111 } 112
Exported from Notepad++
1 // Name: Mostapha Abdelaziz 2 // Class: CST8132 #303 3 // 4 // Assessment: Lab 8 5 // Description: Class for the Person object to be used as the account holder 6 7 package lab8; 8 9 /** 10 * This class is for a person object to be used as the account holder. 11 * @author Mostapha Abdelaziz 12 * @version 1.0 13 * @since 1.8 14 */ 15 public class Person { 16 // instance variables 17 private String firstName; 18 private String lastName; 19 private String email; 20 private long phoneNumber; 21 22 /** 23 * No argument constructor to be able to create an object without parameters. 24 */ 25 //no argument constructor 26 public Person() { 27 28 } 29 30 // getter method for name 31 /** 32 * Method to access the private variables of first name and last name. 33 * @return return the first name and last name together of the Person. 34 */ 35 public String getName() { 36 String Name = firstName + " " + lastName; 37 return Name; 38 } 39 40 // getter method for email 41 /** 42 * This is a method to access the email address of the Person. 43 * @return return the email address of the Person. 44 */ 45 public String getEmail() { 46 return email; 47 } 48 49 // getter method for phone number 50 /** 51 * This is a method to access the phone number of the person. 52 * @return 53 */ 54 public long getPhoneNumber() { 55 return phoneNumber; 56 } 57 58 //setter method for first name 59 /** 60 * This is a method to set or change the first name of the person. 61 * @param firstName The desired first name to use. 62 */ 63 public void setFirstName(String firstName) { 64 this.firstName = firstName; 65 } 66 67 //setter method for last name 68 /** 69 * This is a method to set or change the last name of the person. 70 * @param lastName The desired last name to use. 71 */ 72 public void setLastName(String lastName) { 73 this.lastName = lastName; 74 } 75 76 //setter method for email 77 /** 78 * This method is for setting or changing the email address of the person. 79 * @param email The desired email to use. 80 */ 81 public void setEmail(String email) { 82 this.email = email; 83 } 84 85 //setter method for phone number 86 /** 87 * This method is to set or change the phone number of the person. 88 * @param phoneNumber The desired phone number to use. 89 */ 90 public void setPhoneNumber(long phoneNumber) { 91 this.phoneNumber = phoneNumber; 92 } 93 } 94
Exported from Notepad++
1 // Name: Mostapha Abdelaziz 2 // Class: CST8132 #303 3 // 4 // Assessment: Lab 8 5 // Description: Abstract class to be used as the basis for savings and chequing accounts 6 7 package lab8; 8 9 import java.text.DecimalFormat; 10 import java.util.InputMismatchException; 11 import java.util.Scanner; 12 13 /** 14 * Bank account class to be extended by savings and chequing accounts. Contains 15 * the common attributes and behaviours. 16 * 17 * @author Mostapha Abdelaziz 18 * @version 1.1 19 * @since 1.8 20 * @see Person 21 */ 22 abstract class BankAccount { 23 // instance variables 24 /** The bank account number, up to 8 digits **/ 25 protected long accountNumber; 26 /** The account holder, an object of class Person **/ 27 protected Person accHolder = new Person(); 28 /** The balance of amount of funds available in the account **/ 29 protected double balance; 30 /** The type of account, chequing or savings **/ 31 protected String type; 32 /** The fee for a chequing account, to be used in chequing account **/ 33 protected double fee; 34 /** The minimum balance for a savings account **/ 35 protected double minBalance; 36 /** The interest rate for a savings account **/ 37 protected double interestRate; 38 39 // no argument constructor 40 /** 41 * No argument constructor to create a bank account without parameters. 42 */ 43 BankAccount() { 44 } 45 46 // return the data of the account 47 /** 48 * Return a formatted string of all the account information. 49 * 50 * @return The formatted string of all information 51 */ 52 public String toString() { 53 // for formatting balance 54 DecimalFormat format = new DecimalFormat("0.##"); 55 56 // add all the details to one string 57 String details; 58 details = type + " | AccountNumber: " + accountNumber + " | Name: " 59 + accHolder.getName() + " | Phone Number: " + accHolder.getPhoneNumber() 60 + " | Email Address: " + accHolder.getEmail() + " | Balance: " 61 + format.format(balance); 62 63 // return string 64 return details; 65 } 66 67 // method for adding a bank account to the array 68 /** 69 * Take input from the user and create a new Bank Account. 70 * 71 * @param input A scanner object named input to take in the input of the user 72 * @return A boolean value of whether it was successful or not. 73 */ 74 public boolean addBankAccount(Scanner input) { 75 boolean loop = true; 76 // ask for and store input to create a new account 77 78 // account holder details 79 System.out.print("Enter first name of account holder : "); 80 accHolder.setFirstName(input.next()); 81 82 System.out.print("Enter last name of account holder : "); 83 accHolder.setLastName(input.next()); 84 85 // loop for valid input for a phone number 86 do { 87 System.out.print("Enter phone number of account holder : "); 88 // try the input and catch errors 89 try { 90 accHolder.setPhoneNumber(input.nextLong()); 91 loop = false; 92 } catch (InputMismatchException e) { 93 // print error and exception 94 System.err.println(e+ ": This is not a number, try again."); 95 input.nextLine(); 96 } 97 } while (loop == true); 98 //reset loop variable 99 loop = true; 100 101 //prompt for input 102 System.out.print("Enter email of account holder : "); 103 accHolder.setEmail(input.next()); 104 105 // loop for valid input for a opening balance 106 do { 107 System.out.print("Enter opening balance of account holder : "); 108 // try the input and catch errors 109 try { 110 balance = input.nextDouble(); 111 loop = false; 112 } catch (InputMismatchException e) { 113 // print error and exception 114 System.err.println(e+ ": This is not a number, try again."); 115 input.nextLine(); 116 } 117 } while (loop == true); 118 119 // return boolean value to be used next lab 120 return false; 121 } 122 123 // withdraw or deposit from the account 124 /** 125 * Update the balance of the account based on a withdrawal or a deposit. 126 * 127 * @param The amount withdrawn or deposited. 128 */ 129 public void updateBalance(double changes) { 130 // add or subtract from current balance 131 balance = balance + changes; 132 } 133 134 // abstract to be used in sub classes 135 /** 136 * Perform the necessary calculations for any monthly fees or interest. 137 */ 138 public abstract void monthlyAccountUpdate(); 139 } 140
Exported from Notepad++
1 // Name: Mostapha Abdelaziz 2 // Class: CST8132 #303 3 // 4 // Assessment: Lab 8 5 // Description: Class for Chequing account, 6 // extend Bank account and adds chequing specific behaviours and attributes 7 8 package lab8; 9 10 import java.text.DecimalFormat; 11 import java.util.InputMismatchException; 12 import java.util.Scanner; 13 14 /** 15 * A class for a chequing account, extends the Bank account and adds additional 16 * chequing specific functionality. 17 * 18 * @author Mostapha Abdelaziz 19 * @version 1.1 20 * @since 1.8 21 * @see BankAccount 22 */ 23 public class ChequingAccount extends BankAccount { 24 25 // no argument constructor 26 /** 27 * No argument constructor to be able to create an object and set the variables at a later date. 28 */ 29 ChequingAccount() { 30 //set the type to chequing 31 type = "C"; 32 } 33 34 // return the data of the account 35 /** 36 * Return a formatted string of all the account information. Uses the super 37 * method and adds on to it. 38 * 39 * @return The formatted string of all information 40 */ 41 public String toString() { 42 DecimalFormat format = new DecimalFormat("0.0#"); 43 // add all the details to one string 44 String details; 45 details = super.toString() + " | Fee: " + format.format(fee); 46 47 // return string 48 return details; 49 } 50 51 // add a new bank account 52 /** 53 * Take input from the user and create a new Bank Account. Uses the super method 54 * and adds on to it. 55 * 56 * @return A boolean value of whether it was successful or not 57 */ 58 public boolean addBankAccount(Scanner input) { 59 boolean loop = true; 60 // ask for and store input to create a new account 61 // call super method for non checking specific information 62 super.addBankAccount(input); 63 64 // chequing specific information 65 // loop for valid input for an monthly fee 66 do { 67 System.out.print("Enter the Chequing Account's monthly fee : "); 68 // try the input and catch errors 69 try { 70 fee = input.nextDouble(); 71 if (fee < 0) { 72 throw new ArithmeticException("Monthly fees must be a positive value."); 73 } 74 loop = false; 75 } catch (InputMismatchException e) { 76 // print error and exception 77 System.err.println(e+ ": This is not a number, try again."); 78 input.nextLine(); 79 } catch (ArithmeticException e) { 80 // print error and exception 81 System.out.println(e); 82 input.nextLine(); 83 } 84 } while (loop == true); 85 86 // return boolean value to be used next lab 87 return true; 88 } 89 90 // perform monthly updates 91 /** 92 * Perform the necessary calculations for subtracting any fees from the balance. 93 */ 94 public void monthlyAccountUpdate() { 95 // if statement to determine if balance has enough for fees 96 if (balance >= fee) { 97 // subtract fee from balance 98 balance = balance - fee; 99 } else { 100 // display error message 101 System.out.println( 102 "Account " + accountNumber + " does not have enough balance to subtract the fees of " + fee); 103 } 104 } 105 106 } 107
Exported from Notepad++
1 // Name: Mostapha Abdelaziz 2 // Class: CST8132 #303 3 // Professor: Daniel Cormier 4 // Assessment: Lab 8 5 // Description: Class for Savings account, 6 // extend Bank account and adds savings specific behaviours and attributes 7 8 package lab8; 9 10 import java.text.DecimalFormat; 11 import java.util.InputMismatchException; 12 import java.util.Scanner; 13 14 /** 15 * A class for a savings account, extends the Bank account and adds additional 16 * savings specific functionality. 17 * 18 * @author Mostapha Abdelaziz 19 * @version 1.1 20 * @since 1.8 21 * @see BankAccount 22 */ 23 public class SavingsAccount extends BankAccount { 24 25 // no argument constructor 26 /** 27 * No argument constructor to be able to create an object without parameters. 28 */ 29 SavingsAccount() { 30 //set the account type 31 type = "S"; 32 } 33 34 // return the data of the account 35 /** 36 * Return a formatted string of all the account information. Uses the super 37 * method and adds on to it. 38 * 39 * @return The formatted string of all information 40 */ 41 public String toString() { 42 DecimalFormat format = new DecimalFormat("0.0#"); 43 // add all the details to one string 44 String details; 45 details = super.toString() + " | Minimum Balance: " + format.format(minBalance) + " | Interest Rate: " 46 + format.format(interestRate); 47 48 // return string 49 return details; 50 } 51 52 // add a new bank account 53 /** 54 * Take input from the user and create a new Bank Account. Uses the super method 55 * and adds on to it. 56 * 57 * @return A boolean value of whether it was successful or not 58 */ 59 public boolean addBankAccount(Scanner input) { 60 boolean loop = true; 61 // ask for and store input to create a new account 62 // call super method for non savings specific information 63 super.addBankAccount(input); 64 65 // savings specific information 66 // loop for valid input for a minimum balance 67 do { 68 System.out.print("Enter the Saving Account's minimum balance : "); 69 // try the input and catch errors 70 try { 71 minBalance = input.nextDouble(); 72 loop = false; 73 } catch (InputMismatchException e) { 74 // print error and exception 75 System.out.println(e+ ": This is not a number, try again."); 76 input.nextLine(); 77 } 78 } while (loop == true); 79 //reset loop variable 80 loop = true; 81 82 // loop for valid input for an interest rate 83 do { 84 System.out.print("Enter the Saving Account's Yearly interest rate (should be a number in (0,1)) : "); 85 // try the input and catch errors 86 try { 87 interestRate = input.nextDouble(); 88 if (interestRate > 1 || interestRate < 0) { 89 throw new ArithmeticException(); 90 } 91 loop = false; 92 } catch (InputMismatchException e) { 93 // print error and exception 94 System.out.println(e+ ": This is not a number, try again."); 95 input.nextLine(); 96 } catch (ArithmeticException e) { 97 // print error and exception 98 System.err.println("Interest rate must be a value between 0 and 1.\n" +e); 99 input.nextLine(); 100 } 101 } while (loop == true); 102 103 // return boolean value to be used next lab 104 return true; 105 } 106 107 // perform monthly updates 108 /** 109 * Perform the necessary calculations for the monthly interest and add to the 110 * balance. 111 */ 112 public void monthlyAccountUpdate() { 113 // if statement to determine if balance is above minimum for interest 114 if (balance >= minBalance) { 115 // add interest, divided by 12 because it is a yearly rate and this is a monthly 116 // update 117 balance = ((balance * interestRate) / 12) + balance; 118 } else { 119 // display error message 120 System.out.println( 121 "Account " + accountNumber + " does not have the " + minBalance + " required to apply interest"); 122 } 123 124 } 125 126 } 127
Exported from Notepad++
1 // Name: Mostapha Abdelaziz 2 // Class: CST8132 #303 3 // 4 // Assessment: Lab 8 5 // Description: Class for an array of bank accounts, executes their functions as well 6 7 package lab8; 8 9 import java.io.FileNotFoundException; 10 import java.io.IOException; 11 import java.nio.file.Paths; 12 import java.util.ArrayList; 13 import java.util.Formatter; 14 import java.util.InputMismatchException; 15 import java.util.Scanner; 16 17 /** 18 * A class for the Bank, using an array list to keep track of multiple accounts. 19 * Uses the bank account methods to execute all necessary actions. 20 * 21 * @author Mostapha Abdelaziz 22 * @version 1.1 23 * @since 1.8 24 * @see BankAccount, ChequingAccount, SavingsAccount 25 */ 26 public class Bank { 27 // instance variable 28 private ArrayList<BankAccount> accounts = new ArrayList<BankAccount>(); 29 private Scanner input; 30 private Scanner fileInput; 31 private static Formatter output; 32 // testing variable 33 private Boolean success; 34 35 // constructor that takes in a scanner 36 /** 37 * Constructor to create an object. 38 * 39 * @param input A scanner object. Taken from main method to be able to close the 40 * stream once in the main method without errors. 41 */ 42 Bank(Scanner input) { 43 this.input = input; 44 } 45 46 // check account type and add to array 47 /** 48 * Add an account to the array list and use their methods to collect the 49 * information. 50 * 51 * @return Whether adding an account was successful or not 52 */ 53 public boolean addAccount() { 54 boolean success = false; 55 // variable to store input 56 String type = " "; 57 // loop condition 58 Boolean loop = true; 59 60 // header 61 System.out.println("Enter the details of account Holder " + (accounts.size() + 1) 62 + "\n=================================\n"); 63 64 // ask for account type, loop to catch exceptions and validate input 65 do { 66 // prompt 67 System.out.print("Please select the type of account you wish to add. \n" 68 + "Type (without quotations) 'c' for chequing account or 's' for savings account : "); 69 // try the input and catch errors 70 try { 71 type = input.nextLine(); 72 // if it a valid choice, set loop condition to exit loop 73 if (type.equalsIgnoreCase("c") || type.equals("s")) { 74 loop = false; 75 } else { 76 // else throw exception 77 throw new WrongMenuException(); 78 } 79 } catch (WrongMenuException e) { 80 // print error and exception 81 System.out.println(e); 82 } 83 84 } while (loop == true); 85 // reset loop variable 86 loop = true; 87 88 // variable to store the bank account 89 BankAccount account; 90 // determine which array object needs to be created based on account type 91 if (type.equalsIgnoreCase("c")) { 92 // if they selected Checking type, create a checking 93 account = new ChequingAccount(); 94 accounts.add(account); 95 } else { 96 // if they selected savings type, create a savings 97 account = new SavingsAccount(); 98 accounts.add(account); 99 } 100 101 // ask for account number here, to check with other account numbers, ensure its 102 // not taken 103 long inputAccNumber = -1; 104 do { 105 // try the input and catch any errors 106 try { 107 System.out.print("Enter account number (up to 8 digits) : "); 108 inputAccNumber = input.nextLong(); 109 if (inputAccNumber > 99999999) { 110 throw new DigitAccountNumberException(); 111 } else if (inputAccNumber < 0) { 112 throw new NegativeAccountNumberException(); 113 } else { 114 int arrayIndex; 115 // check if we have this account or not 116 arrayIndex = findAccount(inputAccNumber); 117 // if the account was found, index doesn't equal -1, throw exception 118 if (arrayIndex != -1) { 119 throw new DuplicateAccountNumberException(); 120 } 121 // if no exceptions were thrown exit loop 122 loop = false; 123 } 124 } catch (InputMismatchException e) { 125 // print error and exception 126 System.err.println("Input is Wrong! :You must provide an integer value\n" + e); 127 input.nextLine(); 128 } catch (DigitAccountNumberException e) { 129 // print error and exception 130 System.out.println(e); 131 input.nextLine(); 132 } catch (NegativeAccountNumberException e) { 133 // print error and exception 134 System.out.println(e); 135 input.nextLine(); 136 } catch (DuplicateAccountNumberException e) { 137 // print error and exception 138 System.out.println(e); 139 input.nextLine(); 140 } 141 } while (loop == true); 142 // set the validated account number to the account 143 account.accountNumber = inputAccNumber; 144 145 // call method to read rest of the info 146 account.addBankAccount(input); 147 148 // success is true 149 success = true; 150 return success; 151 } 152 153 // find a specific account 154 /** 155 * Compare a provided account number with the account numbers in our bank 156 * 157 * @return The index value of which the account is stored, or -1 for an error. 158 */ 159 private int findAccount(long accountNumber) { 160 int arrayIndex = -1; 161 162 // check if we have this account or not 163 for (int i = 0; i < accounts.size(); i++) { 164 if (accounts.get(i).accountNumber == accountNumber) { 165 arrayIndex = i; 166 i = accounts.size(); 167 } 168 } 169 170 // return the index number or -1 171 return arrayIndex; 172 } 173 174 // use account number to display account 175 /** 176 * Uses the findAccount method to return a string of a specific accounts 177 * information or an error message. 178 * 179 * @return The string with an error message or account information. 180 */ 181 public String displayAccount() { 182 int arrayIndex = -1; 183 String info = null; 184 long account = 0; 185 boolean loop = true; 186 187 // ask for account number, loop for input 188 do { 189 System.out.print("Please enter an account number to display the information of : "); 190 // try this input and catch errors 191 try { 192 account = input.nextLong(); 193 if (account > 99999999) { 194 throw new DigitAccountNumberException(); 195 } else if (account < 0) { 196 throw new NegativeAccountNumberException(); 197 } else { 198 arrayIndex = findAccount(account); 199 if (arrayIndex == -1) { 200 throw new NotExistAccountException(); 201 } else { 202 loop = false; 203 } 204 } 205 } catch (InputMismatchException e) { 206 // print error and exception 207 System.err.println(e + ": This is not a number, try again."); 208 } catch (DigitAccountNumberException e) { 209 // print error and exception 210 System.out.println(e); 211 } catch (NegativeAccountNumberException e) { 212 // print error and exception 213 System.out.println(e); 214 } catch (NotExistAccountException e) { 215 // store error and exception, exit loop 216 info = e + "\nReturning to main menu..."; 217 loop = false; 218 } 219 } while (loop == true); 220 221 // if the array was not found return error message, else return the information 222 if (arrayIndex == -1) { 223 // info was already given the error string 224 } else { 225 info = accounts.get(arrayIndex).toString(); 226 } 227 228 // return the string of error or account info 229 return info; 230 } 231 232 // print all account details 233 /** 234 * Uses a loop to print all the information of every account in our bank array. 235 */ 236 public void printAccountDetails() { 237 // Header 238 System.out.println( 239 "Banking System\n" + "******************\n" + "Number of Account Holders : " + accounts.size() + "\n"); 240 //open the output file to write to 241 openOutputFile(); 242 // print each index of the array 243 for (int i = 0; i < accounts.size(); i++) { 244 // print to console 245 System.out.print(accounts.get(i).toString()+"\n"); 246 // write to file, opening then closing 247 writeIntoFile(accounts.get(i).toString()); 248 } 249 //close the file 250 closeOutputFile(); 251 } 252 253 // use account number to update an account 254 /** 255 * Asks for a withdrawal or deposit and updates the balance of the account 256 * accordingly. 257 */ 258 public void updateAccount() { 259 int arrayIndex = -1; 260 double changes; 261 long account; 262 String info = " "; 263 boolean loop = true; 264 265 // ask for account number, loop for input 266 do { 267 System.out.print("Please enter an account number to update the balance of : "); 268 // try this input and catch errors 269 try { 270 account = input.nextLong(); 271 if (account > 99999999) { 272 throw new DigitAccountNumberException(); 273 } else if (account < 0) { 274 throw new NegativeAccountNumberException(); 275 } else { 276 arrayIndex = findAccount(account); 277 if (arrayIndex == -1) { 278 throw new NotExistAccountException(); 279 } else { 280 loop = false; 281 } 282 } 283 } catch (InputMismatchException e) { 284 // print error and exception 285 System.err.println(e + ": This is not a number, try again."); 286 } catch (DigitAccountNumberException e) { 287 // print error and exception 288 System.out.println(e); 289 } catch (NegativeAccountNumberException e) { 290 // print error and exception 291 System.out.println(e); 292 } catch (NotExistAccountException e) { 293 // store error and exception, exit loop 294 info = e + "\nReturning to main menu..."; 295 loop = false; 296 } 297 } while (loop == true); 298 299 // if the array was not found return error message, else ask for the changes and 300 // execute 301 if (arrayIndex == -1) { 302 System.out.println(info); 303 } else { 304 // ask for change 305 System.out.print("Enter the amount to deposit/withdraw " 306 + "(positive number to deposit, negative number to withdraw) \n"); 307 // try the input and catch exceptions 308 try { 309 changes = input.nextDouble(); 310 // check if you have enough balance for withdrawals 311 if ((changes * -1) > accounts.get(arrayIndex).balance) { 312 throw new InsufficientFundsException((changes * -1) - accounts.get(arrayIndex).balance); 313 } else { 314 // update account 315 accounts.get(arrayIndex).updateBalance(changes); 316 } 317 } catch (InputMismatchException e) { 318 // print error and exception 319 System.err.println(e + ": This is not a number, try again."); 320 } catch (InsufficientFundsException e) { 321 // print error and exception 322 System.out.println(e); 323 } 324 } 325 } 326 327 // process monthly update for all accounts 328 /** 329 * Perform all the necessary calculations for fees or interest on all accounts 330 * in our array. 331 */ 332 public void monthlyUpdate() { 333 // update each index of the array 334 for (int i = 0; i < accounts.size(); i++) { 335 accounts.get(i).monthlyAccountUpdate(); 336 } 337 } 338 339 // this is to open output file 340 /** 341 * Opens the file that we are taking input from. 342 */ 343 public void openInputFile() { 344 try { 345 // file location is relative, uses the Eclipse project root folder (or the grandparent folder) 346 fileInput = new Scanner(Paths.get(".\\bankInput.txt")); 347 success = true; 348 } catch (FileNotFoundException e) { 349 System.err.println("error, file not found"); 350 success = false; 351 } catch (IOException e) { 352 System.err.println("error, IOException"); 353 success = false; 354 } 355 } 356 357 // reads from the open file 358 /** 359 * Reads from the file we are taking input from. 360 */ 361 public void readFromFile() { 362 // to test the type 363 String type; 364 // open the file 365 openInputFile(); 366 367 // loop until there are no more entries in the file 368 while (success == true && fileInput.hasNext()) { 369 // variable to determine account type 370 type = fileInput.next(); 371 372 // variable to store the bank account 373 BankAccount account; 374 // determine which array object needs to be created based on account type 375 if (type.equalsIgnoreCase("c")) { 376 // if they selected Chequing type, create a chequing 377 account = new ChequingAccount(); 378 // set the values from the file 379 // take the account number 380 account.accountNumber = Long.parseLong(fileInput.next()); 381 // take the first name 382 account.accHolder.setFirstName(fileInput.next()); 383 // take the last name 384 account.accHolder.setLastName(fileInput.next()); 385 // take the phone number 386 account.accHolder.setPhoneNumber(Long.parseLong(fileInput.next())); 387 // take the email 388 account.accHolder.setEmail(fileInput.next()); 389 // take the balance 390 account.balance = Double.parseDouble(fileInput.next()); 391 // take the fee 392 account.fee = Double.parseDouble(fileInput.next()); 393 394 } else { 395 // if they selected savings type, create a savings 396 account = new SavingsAccount(); 397 // set the values from the file 398 // take the account number 399 account.accountNumber = Long.parseLong(fileInput.next()); 400 // take the first name 401 account.accHolder.setFirstName(fileInput.next()); 402 // take the last name 403 account.accHolder.setLastName(fileInput.next()); 404 // take the phone number 405 account.accHolder.setPhoneNumber(Long.parseLong(fileInput.next())); 406 // take the email 407 account.accHolder.setEmail(fileInput.next()); 408 // take the balance 409 account.balance = Double.parseDouble(fileInput.next()); 410 // take the minimum balance 411 account.minBalance = Double.parseDouble(fileInput.next()); 412 // take the interest rate 413 account.interestRate = Double.parseDouble(fileInput.next()); 414 } 415 416 // add the created account to the array 417 accounts.add(account); 418 } 419 420 // close the file if it was opened 421 if (success == true) { 422 closeInputFile(); 423 } 424 } 425 426 // closes the file we opened for input 427 /** 428 * Closes the file we were taking input from. 429 */ 430 public void closeInputFile() { 431 if (fileInput != null) { 432 fileInput.close(); 433 } 434 } 435 436 // opens the file that we will be writing in 437 /** 438 * Opens the file that we will be writing our information to. 439 */ 440 public void openOutputFile() { 441 try { 442 // file location is relative, uses the Eclipse project root folder (or the grandparent folder) 443 output = new Formatter(".\\bankOutput.txt"); 444 success = true; 445 } catch (SecurityException e) { 446 System.err.println("error, not allowed"); 447 success = false; 448 } catch (FileNotFoundException e) { 449 System.err.println("error, file not found"); 450 success = false; 451 } 452 } 453 454 // writes into the open file 455 /** 456 * Writes into the file we have opened. 457 * 458 * @param info The string of account information to be written into the file. 459 */ 460 public void writeIntoFile(String info) { 461 // if the file was opened successfully 462 if (success == true) { 463 // takes the string and prints into file 464 output.format("%s\n", info); 465 } 466 } 467 468 // closes the output file 469 /** 470 * Closes the file we have written into. 471 */ 472 public void closeOutputFile() { 473 //if the file was opened successfully output is not null close 474 if (success == true && output != null) { 475 output.close(); 476 } 477 } 478 }
Exported from Notepad++
1 // Name: Mostapha Abdelaziz 2 // Class: CST8132 #303 3 // 4 // Assessment: Lab 8 5 // Description: Class to throw an exception, extends exception 6 7 package lab8; 8 9 /** 10 * Throws a more detailed exception, extends Exception. For when the account number doesn't fit the format. 11 * @author Mostapha Abdelaziz 12 * @version 1.0 13 * @since 1.8 14 * @see Exception 15 */ 16 public class DigitAccountNumberException extends Exception { 17 /** 18 * To satisfy compiler warning. 19 */ 20 private static final long serialVersionUID = 5749603824235195376L; 21 22 /** 23 * Throw an exception for when the account number doesn't fit the format 24 */ 25 public DigitAccountNumberException() { 26 System.err.println("Please enter an account number that is 8 digits or less:"); 27 } 28 } 29
Exported from Notepad++
1 // Name: Mostapha Abdelaziz 2 // Class: CST8132 #303 3 // 4 // Assessment: Lab 8 5 // Description: Class to throw an exception, extends exception 6 7 package lab8; 8 9 /** 10 * Throws a more detailed exception, extends Exception. For when there is an account with the same number. 11 * @author Mostapha Abdelaziz 12 * @version 1.0 13 * @since 1.8 14 * @see Exception 15 */ 16 public class DuplicateAccountNumberException extends Exception { 17 18 /** 19 * To satisfy compiler warning. 20 */ 21 private static final long serialVersionUID = 5749603824235195376L; 22 23 /** 24 * Throw an exception for when there is an account with the same number 25 */ 26 public DuplicateAccountNumberException() { 27 System.err.println("That account number is already used, Please enter another account number :"); 28 } 29 } 30
Exported from Notepad++
1 // Name: Mostapha Abdelaziz 2 // Class: CST8132 #303 3 // 4 // Assessment: Lab 8 5 // Description: Class to throw an exception, extends exception 6 7 package lab8; 8 9 /** 10 * Throws a more detailed exception, extends Exception. For when there are insufficient funds. 11 * @author Mostapha Abdelaziz 12 * @version 1.0 13 * @since 1.8 14 * @see Exception 15 */ 16 public class InsufficientFundsException extends Exception { 17 /** 18 * To satisfy compiler warning. 19 */ 20 private static final long serialVersionUID = 5749603824235195376L; 21 22 //to store the amount the account is short by 23 private double shortAmount; 24 25 /** 26 * Throw exception for when there are insufficient funds. 27 * @param shortAmount How much money you are short by for a withdrawal. 28 */ 29 public InsufficientFundsException(double shortAmount) { 30 this.shortAmount = shortAmount; 31 System.err.println("You are unable to withdraw money as you are short $" 32 +String.format("%.1f", shortAmount)+ "."); 33 } 34 35 /** 36 * Return the amount short by. 37 * @return The amount you are short by. 38 */ 39 public double getShortAmount() { 40 return shortAmount; 41 } 42 } 43
Exported from Notepad++
1 // Name: Mostapha Abdelaziz 2 // Class: CST8132 #303 3 // 4 // Assessment: Lab 8 5 // Description: Class to throw an exception, extends exception 6 7 package lab8; 8 9 /** 10 * Throws a more detailed exception, extends Exception. For when the account number is negative. 11 * @author Mostapha Abdelaziz 12 * @version 1.0 13 * @since 1.8 14 * @see Exception 15 */ 16 public class NegativeAccountNumberException extends Exception { 17 18 /** 19 * To satisfy compiler warning. 20 */ 21 private static final long serialVersionUID = 5749603824235195376L; 22 23 /** 24 * Throw an exception when the account number is negative 25 */ 26 public NegativeAccountNumberException () { 27 System.err.println("Please enter a positive integer value for the account number :"); 28 } 29 } 30
Exported from Notepad++
1 // Name: Mostapha Abdelaziz 2 // Class: CST8132 #303 3 // 4 // Assessment: Lab 8 5 // Description: Class to throw an exception, extends exception 6 7 package lab8; 8 9 /** 10 * Throws a more detailed exception, extends Exception. For when the account number is negative. 11 * @author Mostapha Abdelaziz 12 * @version 1.0 13 * @since 1.8 14 * @see Exception 15 */ 16 public class NegativeAccountNumberException extends Exception { 17 18 /** 19 * To satisfy compiler warning. 20 */ 21 private static final long serialVersionUID = 5749603824235195376L; 22 23 /** 24 * Throw an exception when the account number is negative 25 */ 26 public NegativeAccountNumberException () { 27 System.err.println("Please enter a positive integer value for the account number :"); 28 } 29 } 30
Exported from Notepad++
1 // Name: Mostapha Abdelaziz 2 // Class: CST8132 #303 3 // 4 // Assessment: Lab 8 5 // Description: Class to throw an exception, extends exception 6 7 package lab8; 8 9 /** 10 * Throws a more detailed exception, extends Exception. For when the wrong menu option is used. 11 * @author Mostapha Abdelaziz 12 * @version 1.0 13 * @since 1.8 14 * @see Exception 15 */ 16 public class WrongMenuException extends Exception { 17 18 /** 19 * To satisfy compiler warning. 20 */ 21 private static final long serialVersionUID = 5749603824235195376L; 22 23 /** 24 * Throw an exception when the wrong menu option is used. 25 */ 26 public WrongMenuException() { 27 System.err.println("Wrong Menu Selection: Did not receive one of the listed inputs. " 28 + "Please enter one of the listed inputs."); 29 } 30 31 } 32