package grossmontbank;

import java.util.Scanner;

public class GrossmontBank 
{
    //class variables (global - accessible throughout this class)

    //scanner object to be used throughout
    private static Scanner input = new Scanner(System.in);

    //array of blank accounts
    private static final int MAX_ACCOUNTS = 50;
    private static Account[] accounts = new Account[MAX_ACCOUNTS];

    //total accounts created
    private static int totalAccounts = 0;

    //main class mimics a bank teller 
    public static void main(String[] args) 
    {
        char choice;

        //loop until 'Q' is entered
        do
        {
            choice = getChoice(); //getChoice() will only return with a C, B, W, D or Q
            if(choice != 'Q')
            {
                switch(choice)
                {
                    case 'C':   createAccount();
                                break;

                    case 'B':   checkBalance();
                                break;

                    case 'W':   withdrawal();
                                break;

                    case 'D':   deposit();
                                break;
                    case 'S':   Savings();
                                break;
                }                
            }            
        }while(choice != 'Q');

        closeBank(); //outputs all account holders and 'closes' the bank

    }

    /*method checkBalance  calls method findAccount()
    *                      if account exists, calls Account method checkBalance()
    */
    private static void checkBalance()
    {
        int accountIndex = findAccount();        
        //findAccount() returns index of account if found, -1 if not found
        if(accountIndex != -1)
        {
            accounts[accountIndex].checkBalance();
        }
        else
        {
             System.out.println("Account does not exist");
        }
    }

    /*method checkIfExists  determines if account holder already exists
    *                      returns true if account holder exists, false otherwise
    */   
    private static boolean checkIfExists(String firstName, String lastName)
    {
        //loops through account array to see if account name already exists
        for(int i = 0; i < totalAccounts;i++)
        {
            //compares the names, ignoring upper/lower
            if(accounts[i].getFirstName().equalsIgnoreCase(firstName) 
                    && accounts[i].getLastName().equalsIgnoreCase(lastName))
            {
                System.out.println("Account holder already exists.  Please verify and re-enter. ");
                return true;
            }
        }
        return false;
    }

    /*method closeBank  prints out closing statement
    *                   prints out list of all account holders
    */
    private static void closeBank()
    {
        System.out.println("Closing the follow accounts:");

        for(int i = 0; i < totalAccounts;i++)
        {
            //printing an account object invokes the Account class method toString()
            //prints first and last name only
            System.out.printf("    %s%n",accounts[i]); 
        }        
        System.out.println("Grossmont Bank is officially closed.");        
    }

    private static void createAccount()
    {
        String first, last, initial;
        boolean exists = false;
        double initialDeposit;
        char accountType;

        //check to ensure max accounts hasn't been reached (not necessary if I were to use an ArrayList!)
        if(totalAccounts < MAX_ACCOUNTS )
        {
            //get name and check to ensure doesn't already exist, loop until new name
            do
            {

                System.out.print("Enter your first name: ");
                first = input.next();
                System.out.print("Enter your last name: ");
                last = input.next();
                exists = checkIfExists(first,last);

            }while(exists == true);

            System.out.print("Would you like to create a (C)hecking or (S)avings account? ");
            accountType = input.next().charAt(0);

            System.out.print("Will you be making an initial deposit? Enter Yes or No: ");
            initial = input.next();

            if(initial.equals("No"))
            {
                if(accountType == 'C') //should be for a checking account
                {
                    accounts[totalAccounts] = new Account(first,last); //you will need to change this line!!!!
                }
                else //savings account
                {
                   accounts[totalAccounts] = new Account(first,last);//you will need to change this line!!!!!
                }
            }
            else
            {
                System.out.print("Enter initial deposit amount: ");
                initialDeposit = input.nextDouble();

                if(accountType == 'C') //checking account
                {
                    accounts[totalAccounts] = new Account(first,last, initialDeposit); //you will need to change this line!!!!
                }
                else //savings account
                {
                    accounts[totalAccounts] = new Account(first,last, initialDeposit); //you will need to change this line!!!!!
                }
            }

            totalAccounts++;
        }
        else
        {
            System.out.println("Maximum number of accounts has been reached. ");
        }

    }

    /*method deposit calls method findAccount()
    *                 if account exists, calls Account method withdrawal
    */
    private static void deposit()
    {
        int accountIndex = findAccount();

        //findAccount() returns index of account if found, -1 if not found
        if(accountIndex != -1)
        {
            accounts[accountIndex].deposit();
        }
        else
        {
             System.out.println("Account does not exist");
        }
    }

    /*method findAccount   asks for first and last name
    *                      searchs for account holder in array
    *                      if exists, returns array index of this account
    *                      if doesn't exist, returns '-1'
    *                      called from checkBalance()
    */
    private static int findAccount()
    {
        String first, last;

        System.out.print("Enter first name: ");
        first = input.next();
        System.out.print("Enter last name: ");
        last = input.next();

        //loops through account array
        for(int i = 0; i < totalAccounts;i++)
        {
            //compares the names, ignoring upper/lower
            if(accounts[i].getFirstName().equalsIgnoreCase(first) 
                    && accounts[i].getLastName().equalsIgnoreCase(last))
            {
                return i; //returns the index of the account
            }
        }
        return -1; //if account not found

    }

     /* method getChoice()   outputs options 
    *                       inputs choice from user and validates
    *                       returns choice char
    */                      
    private static char getChoice()
    {
        char choice;

        //output menu options
        System.out.println();
        System.out.println("Welcome to Grossmont Bank.  Choose from the following options: ");
        System.out.println("    C - create new account");
        System.out.println("    B - check your balance");
        System.out.println("    D - deposit");
        System.out.println("    W - withdrawal");
        System.out.println("    S - Savings");
        System.out.println("    Q - quit");

        //loop until a valid input is entered
        do
        {
            System.out.print("Enter choice: ");
            choice = input.next().charAt(0);
            //if choice is one of the options, return it.  Otherwise keep looping
            if(choice == 'C' || choice == 'B' || choice == 'D' || choice == 'W' || choice == 'S' || choice == 'Q')
                return choice;
            else
            {
                System.out.println("Invalid choice.  Ensure a capital letter. Please re-enter.");
                choice = '?';
            }
        }while(choice == '?');

        return choice;  //will never get here, but required to have a return statement to compile   
    }

    /*method withdrawal  calls method findAccount()
    *                 if account exists, calls Account method withdrawal
    */
    private static void withdrawal()
    {
        int accountIndex = findAccount();

        //findAccount() returns index of account if found, -1 if not found
        if(accountIndex != -1)
        {
            accounts[accountIndex].withdrawal();
        }
        else
        {
             System.out.println("Account does not exist");
        }
    }

    private static void Savings()        
    {
        Account a = new Account();
        checkBalance();
        Savings s = new Savings();
        System.out.println("Balance " + a.getbalance());
        withdrawal();        
        System.out.println();
        s.setdeposit(300);
        s.print();
    }
}

    the code above is my main class

package grossmontbank;

import java.time.LocalDateTime;
import java.util.Scanner;
import java.security.SecureRandom; //random generator that is much harder to hack!

public class Account 
{

    //class variables - shared, will be the same for every Account object created
    //having every account know how many total accounts exist isn't really necessary, just demonstrates the ability
    public static int totalAccounts;

    //instance variables
    protected String firstName;
    protected String lastName;
    protected String pin;
    double balance;
    double annualInterestRate = 0;
    private LocalDateTime dateCreated;

    /* Account constructor default
    *
    */
    Account()
    {
        this(null,null,0.0);
    }

    /* Account constructor with no initial balance 
    *
    */
    Account(String first, String last)
    {
        //call the other constructor but use a value of 0 for the balance
        //basically the "this" is being replaced by the current class which is Account
        //yay for reusing code!
        this(first, last, 0.0);
    }

    /* Account constructor with an initial balance
    *
    */
    Account(String first, String last, double initial)
    {
        //set first and last name
        firstName = first;
        lastName = last;

        //set balance to initial amount
        balance = initial;

        //set date created to today
        dateCreated = LocalDateTime.now();

        System.out.println("Your bank account has been created.");
        printBalance();
        System.out.println("Date/Time created: " + dateCreated);

        //generate a new pin number for this account
        generateNewPin();

        //increase the totalAccounts created
        totalAccounts++;
    }

    /* method checkBalance() prints account balance if pin is entered correctly
    *
    */
    public void checkBalance()
    {
        if(verifyPin())
            printBalance();
        else
            System.out.println("Unable to view balance.");
    }

    /* method deposit() checks for pin number, then deposits amount
    *
    */
    public void deposit()
    {
        if(verifyPin())
        {
            double amount; 
            Scanner systemIn = new Scanner(System.in);

            printBalance();

            System.out.print("How much would you like to deposit? ");
            amount = systemIn.nextDouble();
            balance += amount;
            printBalance();    
        }
        else
            System.out.println("Unable to deposit.");
    }

    /* method printBalance()    prints the balance in the current account
    *                           
    */
    protected void printBalance()
    {
        System.out.printf("Your current balance: $%.2f%n",balance);
    }

    /* method generateNewPin()  creates a new random 4 digit pin number
    *                           sets pin and outputs to screen
    */
    private void generateNewPin()
    {
        //create secureRandom object
        SecureRandom randomGenerator = new SecureRandom();

        //generate four random numbers 0-9 converted to a String (maybe a loop would be better??)
        String num1 = new Integer(randomGenerator.nextInt(10)).toString();
        String num2 = new Integer(randomGenerator.nextInt(10)).toString();
        String num3 = new Integer(randomGenerator.nextInt(10)).toString();
        String num4 = new Integer(randomGenerator.nextInt(10)).toString();

        //combine (concatenate) all four number Strings into 1 String
        pin = num1 + num2 + num3 + num4;

        //output
        System.out.printf("Your new pin number is %s.%n",pin);

    }

    /* method getFirstName() returns the first name of the current account
    *
    */
    public String getFirstName()
    {
        return firstName;
    }

    /* method getFullName() returns the full name of the current account
    *
    */
    public String getFullName()
    {
        return firstName + " " + lastName;
    }

    /* method getLastName() returns the last name of the current account
    *
    */
    public String getLastName()
    {
        return lastName;
    }

    /* method toString()    returns a String in the specified format
    *                       will be invoked if the object is printed as a String
    *                       overides printing of the address location
    */
    public String toString()
    {
        return String.format("Account: %s %s",firstName,lastName);
    }

    /* method withdrawal() checks for pin number, then withdrawals amount requested
    *
    */
    public void withdrawal()
    {
        if(verifyPin())
        {
            double amount; 
            Scanner systemIn = new Scanner(System.in);

            printBalance();
            do
            {
                System.out.print("How much would you like to withdrawal? ");
                amount = systemIn.nextDouble();
                if(amount > balance)
                    System.out.println("Withdrawal amount exceeds account balance.");
            }while(amount > balance);

            balance -= amount;
            printBalance();    
        }
        else
            System.out.println("Unable to withdrawal.");
    }

    /* method verifyPin()   asks user to enter pin number
    *                       checks entry with pin
    *                       returns true if correct, false otherwise
    *                       user has three tries to enter correctly
    */
    private boolean verifyPin()
    {
        int maxTimes = 3;
        int times = 0;
        Scanner systemIn = new Scanner(System.in);

        //loops until pin entered correctly or maxed tries reached
        do
        {
            System.out.print("Enter your pin number: ");
            if(systemIn.next().equals(pin))
                return true;
            else
            {
                times++;
                System.out.print("Invalid. ");
            }
        }while(times < maxTimes);

        System.out.println("You have entered your pin incorrectly too many times.");
        return false;
    }
     public double getbalance()
    {
        return balance;
    }
      public void setannualInterestRate(double a)
    {
        annualInterestRate = a;
    }

    public double getannualInterestRate()
    {
        return annualInterestRate;
    }
     public double getmonthlyInterestRate()
    {
        return annualInterestRate / 12;
    }

}

the code above is my Account class 

package grossmontbank;

public class Savings extends Account
{
    double deposit = 0;
    Savings()   
    {
        super(String firstName, String lastName,String Pin, double balance);
        deposit =0 ;
        deposit();
    }
    public void setdeposit(double d)
    {
        if(d > balance)
        {
            System.out.println("Can't deposit a value greater than " +
                    " your balance");
            System.exit(0);
        }
        else
            deposit = d;
            balance += d;
    }
    public double getdeposit()
    {
        return deposit;
    }
    public void print()
    {
        String output = "Deposited " + deposit +
                "\nSavings balance after deposit: " + balance;
        System.out.println(output);
    }
}

If its at all possible if someone can fix any errors i have in my code since its not working and ive been working on it all day but I just cant fix all these errors what Im trying to do is create a subclass that will have a savings account in it 

Recommended Answers

All 2 Replies

let me know if I can make my post any better but there are 3 classes in the post a Main class which is GrossmontBank, Account class, and subclass Savings if there is anything that i can do to make it better to view please let me know as it is my first time using this website and just starting to use it

OK. I don't have time to read 555 lines of code in detail right now, but I did a few spot checks and was very happy with what I saw. This is maybe the highest quality code I have ever seen for such an early-stage learning project (I'm refering to things like standards compliance, use of methods to make code readable etc). You say "the code above is my Account class" but did you write that, or was it supplied as part of the project materials?

In any case.. please be a lot more specific about the errors you want to fix. Some specifications for the savings account would also be useful, because the code, although it's legal Java, doesn't all seem to make sense, eg why can't a deposit exceed the balance? If you start with zero balance you can never deposit anything!

(One error I did notice was line 527 should be a call to the super constructor, but the syntax you have used is the syntax fior a method definition. Maybe just getting tired - it should be easier after you take a good break. )

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.