Arrays and bank accounts in Java

Azdamus picture Azdamus · Aug 16, 2014 · Viewed 24.4k times · Source

I am trying to write a simple Bank Account Management program that does the following:

Creates a new account with Account number and Balance taken from user and stored in an array Selects an account (from the array) Deletes the account selected Withdraw and Deposit into account selected.

Problem: I don't understand what the my mistakes are.

I tried using different types of arrays for account number and balance storing, but I didn't not find the answer yet. I search the web and Stackoverflow for references, documentations, simple examples, but could not find any (the ones that I found, use some commands and things that I haven't learned yet so I can understand how they work). I am a beginner, I am still learning and would appreciate some advice. Thanks!

//Bank account class
public class account {
private int ANumber;
private double balance;

public account(double initialBalance, int accno) {
    balance = initialBalance;
    ANumber = accno;
}

public void deposit (double u_amm){
    balance += u_amm;
}

public double withdraw(double amount) {
    balance -= amount;
    return amount;
}

public double getBalance() {
    return balance;
}
public int getAccount(){
    return ANumber;
}
}

And this is the Main class

 import java.util.Scanner;
 // main class
 public class bankmain {
 public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    // Menu starts from here
    Scanner input = new Scanner(System.in);
    System.out.println("Enter the option for the operation you need:");
    System.out.println("****************************************************");
    System.out.println("[ Options: ne - New Account de - Delete Account ]");
    System.out.println("[       dp - Deposit    wi - Withdraw      ]");
    System.out.println("[           se - Select Account ex - Quit      ]");
    System.out.println("****************************************************");
    System.out.print("> ");  //indicator for user input
    String choice = input.next();
    //Options
    while(true){
  if(choice == "ne"){
    int nacc;
    int bal;
    int [][]array = new int[nacc][bal];   // Array for account and balance
    System.out.print("Insert account number: ");
    nacc =input.nextInt(); //-- Input nr for array insertion
    System.out.print("Enter initial balance: ");
    bal=input.nextInt(); //-- Input nr for array insertion
    System.out.println("Current account: " + nacc + " " +  "Balance " + bal);
    break;
  }
  // account selection      
  if(choice.equals("se")){
    System.out.println("Enter number of account to be selected: ");
    //user input for account nr from array
    System.out.println("Account closed.");
  }     
  //close account
  if(choice.equals("de")){
    //array selected for closing
    System.out.println("Account closed.");
  }
  // deposit
  if(choice.equals("dp")){
    System.out.print("Enter amount to deposit:  ");
    double amount = scan.nextDouble();
    if(amount <= 0){
        System.out.println("You must deposit an amount greater than 0.");
    } else {
        System.out.println("You have deposited " + (amount + account.getBalance()));
    }
  }
  // withdrawal     
  if(choice.equals("wi")){
    System.out.print("Enter amount to be withdrawn: ");
    double amount = scan.nextDouble();
        if (amount > account.balance()){ 
            System.out.println("You can't withdraw that amount!");
   } else if (amount <= account.balance()) {
    account.withdraw(amount);
    System.out.println("NewBalance = " + account.getBalance());
   }
   }
//quit 
if(choice == "ex"){
    System.exit(0);
        } 
    }   // end of menu loop
 }// end of main
 } // end of class

Answer

Michał Schielmann picture Michał Schielmann · Aug 16, 2014

Your code was wrong on many levels - first try to work on your formatting and naming conventions so you don't learn bad habbits. Dont use small leters for naming classes, try to use full words to describe variables and fields, like in that Account.class example:

public class Account  {
    private Integer accountNumber;
    private Double balance;

    public Account(final Integer accountNumber, final Double initialBalance) {
        this.accountNumber = accountNumber;
        balance = initialBalance;
    }

    public Double deposit (double depositAmmount) {
        balance += depositAmmount;
        return balance;
    }

    public Double withdraw(double withdrawAmmount) {
        balance -= withdrawAmmount;
        return balance;
    }

    public Double getBalance() {
        return balance;
    }

    public Integer getAccountNumber() {
        return accountNumber;
    }
}

Also try to use the same formatting(ie. spaces after brackets) in all code, so that it's simpler for you to read.

Now - what was wrong in your app:

  1. Define the proper holder for your accounts i.e. HashMap that will hold the information about all accounts and will be able to find them by accountNumber.

    HashMap<Integer, Account> accountMap = new HashMap<Integer, Account>();

  2. This one should be inside your while loop, as you want your user to do multiple tasks. You could ommit the println's but then the user would have to go back to the top of the screen to see the options.

    System.out.println("Enter the option for the operation you need:");
    System.out.println("****************************************************");
    System.out.println("[ Options: ne - New Account de - Delete Account ]");
    System.out.println("[       dp - Deposit    wi - Withdraw      ]");
    System.out.println("[           se - Select Account ex - Quit      ]");
    System.out.println("****************************************************");
    System.out.print("> ");  //indicator for user input
    String choice = input.nextLine();   
    System.out.println("Your choice: " + choice);
    
  3. You shouldn't compare Strings using '==' operator as it may not return expected value. Take a look at: How do I compare strings in Java? or What is the difference between == vs equals() in Java?. For safty use Objects equals instead, ie:

    choice.equals("ne")
    
  4. There was no place where you created the account:

    Account newAccount = new Account(newAccountNumber, initialBalance);
    
  5. You didn't use if-else, just if's. It should look more like that (why to check if the choice is 'wi' if it was already found to be 'ne'):

    if(choice.equals("ne")) {
        //doStuff
    } else if choice.equals("se") {
        //doStuff
    } //and so on.
    
  6. If your using Java version >= 7 then instead of if-else you can use switch to compare Strings.

  7. There was no notification of the wrong option:

    } else {
        System.out.println("Wrong option chosen.");
    }
    
  8. You didn't close your Scanner object. This really doesn't matter here, as it's in main method and will close with it, but it's a matter of good habbits to always close your streams, data sources etc when done using it:

    input.close(); 
    

So the whole code can look like this:

import java.util.HashMap;
import java.util.Scanner;
// main class
public class BankAccount {

    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);
        HashMap<Integer, Account> accountMap = new HashMap<Integer, Account>(); 

         //Options
        while(true) {

            System.out.println("Enter the option for the operation you need:");
            System.out.println("****************************************************");
            System.out.println("[ Options: ne - New Account de - Delete Account ]");
            System.out.println("[       dp - Deposit    wi - Withdraw      ]");
            System.out.println("[           se - Select Account ex - Quit      ]");
            System.out.println("****************************************************");
            System.out.print("> ");  //indicator for user input

            String choice = input.next();   
            System.out.println("Your choice: " + choice);

            if(choice.equals("ne")) {
                Integer newAccountNumber;
                Double initialBalance;
                Account newAccount;

                // Array for account and balance
                System.out.print("Insert account number: ");
                newAccountNumber = input.nextInt(); //-- Input nr for array insertion
                System.out.print("Enter initial balance: ");
                initialBalance=input.nextDouble(); //-- Input nr for array insertion
                newAccount = new Account(newAccountNumber, initialBalance);
                accountMap.put(newAccountNumber, newAccount);
                System.out.println("New Account " + newAccountNumber + " created with balance: " + initialBalance);
            }
            //select account
            else if(choice.equals("se")) {
                System.out.println("Enter number of account to be selected: ");
                Integer accountToGetNumber = input.nextInt();
                Account returnedAccount = accountMap.get(accountToGetNumber);
                if (returnedAccount != null)
                {
                    System.out.println("Account open. Current balance: " + returnedAccount.getBalance());
                }
                else
                {
                    //user input for account nr from array
                    System.out.println("Account does not exist.");
                }
            }
            //close account
            else if(choice.equals("de"))
            {
                System.out.println("Enter number of account to be selected: ");
                Integer accountToDeleteNumber = input.nextInt();
                Account removedAccount = accountMap.remove(accountToDeleteNumber);
                if (removedAccount != null)
                {
                    System.out.println("Account " + removedAccount.getAccountNumber() + " has been closed with balance: " + removedAccount.getBalance());
                }
                else
                {
                    //user input for account nr from array
                    System.out.println("Account does not exist.");
                }
            }
            // deposit
            else if(choice.equals("dp")) {
                System.out.println("Enter number of account to deposit: ");
                Integer accountToDeposit = input.nextInt();
                System.out.print("Enter amount to deposit:  ");
                double amount = input.nextDouble();
                if(amount <= 0){
                    System.out.println("You must deposit an amount greater than 0.");
                } else {
                    accountMap.get(accountToDeposit).deposit(amount);
                    System.out.println("You have deposited " + (amount));
                    System.out.println("Current balance " + accountMap.get(accountToDeposit).getBalance());
                }
            }
            // withdrawal     
            else if(choice.equals("wi")) {
                System.out.println("Enter number of account to withdraw: ");
                Integer accountToWithdraw = input.nextInt();
                System.out.print("Enter amount to withdraw:  ");
                double amount = input.nextDouble();
                if(amount <= 0) {
                    System.out.println("You must deposit an amount greater than 0.");
                } else {
                    accountMap.get(accountToWithdraw).withdraw(amount);
                    System.out.println("You have deposited " + (amount));
                    System.out.println("Current balance " + accountMap.get(accountToWithdraw).getBalance());
                }
            }
            //quit 
            else if(choice.equals("ex")) {
                break;
            } else {
                System.out.println("Wrong option.");
            } //end of if
        } //end of loop

        input.close();
    } //end of main
 } //end of class

There still is much to improve, i.e. input validation - but this should work for the begining.