0

I'm involved in a group assignment where we are supposed to create a bank program. This is our first time programming in java. We are stuck and we are having trouble figuring out how to connect our customer and account classes. They both consist of ArrayLists and we want the customer arraylists to contain the accounts. So that if we delete a customer, the accounts that belong to that customer will also be deleted. Can anyone give us a push in the right direction?

This is our main class which contains the bank menu:

package bank6;

import java.util.Scanner;
import java.util.HashMap;
import java.util.Map;


public class Bankmenu {

public static void main(String[] args) {

    Scanner input = new Scanner(System.in);
    Customer client = new Customer();
    Account bank = new Account();
    Account accs = new Account();


    Customer cust1, cust2, cust3;
    cust1 = new Customer("8905060000", "Henrik");
    cust2 = new Customer("8910210000", "Emelie");
    cust3 = new Customer("8611040000", "Fredrik");

    bank.addNewAccount(cust1);
    bank.addNewAccount(cust2);
    bank.addNewAccount(cust3);

    client.addCustomerAr(cust1);
    client.addCustomerAr(cust2);
    client.addCustomerAr(cust3);

    int ChoiceOne = 0;
    int CustChoice;
    int currentCustomer;
    int currentAccount;
    int amountC;
    int amountD;
    int editCust;
    String personNummer = null;

    String Pnr = "0";
    int AdminChoice;

    /*prompts the user to set ChoiceOne equal to 1 or 2. Hasnextint checks
     if the input is an int. else asks for new input. */
    while (ChoiceOne != 1 && ChoiceOne != 2) {
        System.out.println("Press 1 to login as customer or 2 to login as admin ");
        if (input.hasNextInt()) {
            ChoiceOne = input.nextInt();
            System.out.println();

        } else {
            System.out.println("You must enter number 1 or number 2");
            input.next();
        }//ends else

    }//ends while

    /*
     If the user chooses 1 in the previous question, the user will be sent to
     the interface for the customer. User is then asked to enter his social
     security number and this number will be checked using the Luhn algoritm. Since
     the scanner input is already used we added a new Scanner calleds nexLine
     to deal with custPnr as a string.
     (http://stackoverflow.com/questions/5032356/using-scanner-nextline)
     */
    if (ChoiceOne == 1) {
        //boolean quit=false;

        while ("0".equals(Pnr)) {
            //   System.out.println("Welcome customer. Please login by using your birthdate (yymmddnnnn) ");
            //  Scanner nextLine = new Scanner(System.in);
            //  Pnr = nextLine.nextLine();
            //Luhn.checkLogin(Pnr);
            //Här måste en kontroll med Luhn algoritmen göras.
            // getUserBirthdate();
            boolean CorrectBirthDate = false;

            while (CorrectBirthDate == false) {
                System.out.println("Please enter your birthdate");
                Scanner inception = new Scanner(System.in);
                personNummer = inception.next();
                CorrectBirthDate = Luhn.checkLogin(personNummer);

                if (CorrectBirthDate == false) {
                    System.out.println("Incorrect birthdate. You will be prompted to type it again");
                }
            }
            break;
            /*      }

             Sets "quit" to false and executes quit=true if customer chooses case 0
             */
        }
        boolean quit = false;
        do {
            // boolean quit = false;
            //System.out.println();
            System.out.println("Logged on as " + personNummer);
            System.out.println("1. deposit money");
            System.out.println("2. Withdraw money");
            System.out.println("3. Check balance");
            System.out.print("Your choice, 0 to quit: ");

            CustChoice = input.nextInt();

            switch (CustChoice) {
                case 1: //Deposit money
                    System.out.println(bank.getAccountNumbersFor(personNummer));
                    System.out.println("Enter account number:");
                    currentAccount = input.nextInt();
                    System.out.println("Enter amount to deposit:");
                    amountC = input.nextInt();
                    System.out.println(bank.creditAccount(currentAccount, amountC));
                    System.out.println(bank.getAccountNumbersFor("Henrik"));
                    break;
                case 2://Withdraw money
                    // System.out.println(bank.getAccNosFor(custPnr));
                    bank.getAccountNo();
                    System.out.println("Enter account number:");
                    currentAccount = input.nextInt();
                    System.out.println("Enter amount to withdraw:");
                    amountD = input.nextInt();
                    System.out.println(bank.debitAccount(currentAccount, amountD));
                    System.out.println(bank.getAccountNumbersFor("Henrik"));
                    break;
                case 3://Check ballance and accounts
                    System.out.println(bank.getAccountNumbersFor("Henrik"));
                    break;
                case 0:
                    quit = true;
                    break;
                default:
                    System.out.println("Wrong choice.");
                    break;
            }
            System.out.println();
        } while (!quit);
        System.out.println("Bye!");

    }//ends if
    else if (ChoiceOne == 2) {

        while ("0".equals(Pnr)) {
            boolean CorrectBirthDate = false;

            while (CorrectBirthDate == false) {
                System.out.println("Please enter your birthdate");
                Scanner inception = new Scanner(System.in);
                personNummer = inception.next();
                CorrectBirthDate = Luhn.checkLogin(personNummer);

                if (CorrectBirthDate == false) {
                    System.out.println("Incorrect birthdate. You will be prompted to type it again");
                }
            }
            break;
        }

        //AdminpNr = input.nextInt();
        //Här måste en kontroll av AdminpNr göras med hjälp av Luhn.
        boolean quit = false;
        do {
            System.out.println("1. Add customer");
            System.out.println("2. Add account");
            System.out.println("3. List customer");
            System.out.println("4. List accounts");
            System.out.println("5. Remove customer");
            System.out.println("6. Remove account");
            System.out.print("Your choice, 0 to quit: ");
            AdminChoice = input.nextInt();

            switch (AdminChoice) {
                case 1://add customer
                    int i = 0;
                    do {
                        System.out.println("Skriv in nytt personnummer:");
                        Scanner scan = new Scanner(System.in);

                        Map<String, Customer> testCustomers = new HashMap<String, Customer>();
                        String name = scan.nextLine();

                        //System.out.println("Att arbeta på bank ska vara jobbigt, skriv in det igen:");
                        //String pnummer = scan.nextLine();
                        String pnummer = name;
                        System.out.println("Skriv in namn:");
                        String kundnamn = scan.nextLine();
                        Customer obj = new Customer(pnummer, kundnamn);
                        testCustomers.put(name, obj);
                        client.addCustomerAr(obj);
                        i++;
                    } while (i < 2);
                    break;
                case 2://add account
                    int i2 = 0;
                    do {
                        System.out.println("Skriv in nytt personnummer:");
                        Scanner scan = new Scanner(System.in);

                        Map<Long, Account> testAccs = new HashMap<Long, Account>();
                        Long name = scan.nextLong();

                        //System.out.println("Skriv in personnummer igen:");
                        Long own = name;

                        long bal = 0;
                        Account obt = new Account(own, bal);
                        testAccs.put(name, obt);
                        accs.addAccAr(obt);
                        i2++;
                    } while (i2 < 2);
                    break;
                case 3:// List customer and accounts
                    for (String info : client.getAllClients()) {
                        System.out.println(info);
                    }
                    break;
                case 4:
                    for (Long infoAcc : accs.getAllAccounts()) {
                        System.out.println(infoAcc);
                    }
                    break;
                case 5:
                    // ta bort kund
                    break;
                case 6:
                    // ta bort konto
                    break;
                case 0:
                    quit = true;
                    break;
                default:
                    System.out.println("Wrong choice.");
                    break;
            }

            System.out.println();
        } while (!quit);

        System.out.println("Bye!");

    }//ends else if

}//ends main
 /* private static void getUserBirthdate() {
 boolean CorrectBirthDate = false;

 while (CorrectBirthDate == false) {
 System.out.println("Please enter your birthdate");
 Scanner inception = new Scanner (System.in);
 String personNummer = inception.next();
 CorrectBirthDate = Luhn.checkLogin(personNummer);

 if (CorrectBirthDate == false) {
 System.out.println("Incorrect birthdate. You will be prompted to type it again");
 }
 }
 }
 */

}//ends class

This is our Account class;

package bank6;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.ListIterator;


public class Account {

private ArrayList accounts;
private Object lastAcc;
public String customerSocial;
private Integer balance;
private Integer accountNumber;
private Customer owner;
private Account Customer6; // Association customer/account.
private ArrayList<Account> myAccounts = new ArrayList<Account>();
public Integer deposit;
public Integer withdraw;

static Integer accountNo = 1010;
private Long persnr;
private long balans = 0;

/*Constructor.. A account cannot exist unless it is owned by a customer*/
public Account(Customer owner, Integer balance) {
    this.owner = owner;
    this.balance = balance;
    accountNumber = accountNo++;
}

public Account() {
    accounts = new ArrayList();
}

public Account(Long persnr, long balans) {
    this.persnr = persnr;
    this.balans = balans;
    accountNumber = accountNo++;

}

public Integer getAccountNo() {
    return accountNumber;
}

public String getOwner() {
    return owner.getName();
}

public Customer getOwn() {
    return owner;
}

public Integer getBalance() {
    return balance;
}

//credits the account with an amount of money and returns a string
public String credit(Integer anAmount) {
    balance += anAmount;
    //  return "Account number " + accountNumber + " Has been credited with "+anAmount + " kr.";
    return "   " + anAmount + " kr has been deposited to " + accountNumber + "\n";
}

public boolean canDebit(Integer anAmount) {
    return anAmount <= balance;
}

public String debit(Integer anAmount) {

    if (this.canDebit(anAmount)) {
        balance -= anAmount;
        return "   " + anAmount + " kr has been withdrawn from " + accountNumber + "\n";
    } else {
        return "Account number" + accountNo + "has insufficient funds to debit"
                + anAmount;
    }

}

public void addNewAccount(Customer customer) {
    accounts.add(new Account(customer, 0));
    lastAcc = accounts.get(accounts.size() - 1);
    System.out.println("*** New account created. ***" //+ lastAcc 
            + "\n");

}

public String removeAccount(int accountNumber) {
    boolean found = false;
    String results = "";
    ListIterator iter = accounts.listIterator();
    while (iter.hasNext() && found) {

        Account account = (Account) iter.next();

        if (account.getAccountNo() == accountNumber) {
            found = true; //there is a match stop the loop

            if (account.getBalance() == 0) {
                iter.remove();//remove this account object
                results = "Account number " + accountNumber + " has been removed";
            } else {
                results = "Account number " + accountNumber + " cannot be removed"
                        + "as it has a balance of: " + account.getBalance();
            }
        }//ends if there is a match
    }// end while loop

    if (!found) {
        results = "No such account";
    }
    return results;

}

public String creditAccount(int accountNumber, Integer anAmount) {

    boolean found = false;
    String results = "";
    ListIterator iter = accounts.listIterator();
    while (iter.hasNext() && !found) {
        Account account = (Account) iter.next();
        if (account.getAccountNo() == accountNumber) {
            results = account.credit(anAmount);
            found = true;//stop the loop
        }
    }
    if (!found) {
        results = "No such customer";
    }
    return results;
}

public String debitAccount(int accountNumber, Integer anAmount) {
    boolean found = false;
    String results = "";
    ListIterator iter = accounts.listIterator();
    while (iter.hasNext() && !found) {

        Account account = (Account) iter.next();
        if (account.getAccountNo() == accountNumber) {
            results = account.debit(anAmount);
            found = true;
        }
    }

    if (!found) {
        results = "No such Customer";
    }
    return results;
}

public String getAccountNumbersFor(String CustomerName) {
    String details = CustomerName + " has the followinng accounts: "
            + "\n\n";
    Iterator iter = accounts.iterator();

    //visit all of the accounts in the ArrayList
    while (iter.hasNext()) {
        Account account = (Account) iter.next();
        if (account.getOwner().equals(CustomerName)) {
            details += "   Account number " + account.getAccountNo()
                    + "     Balance " + account.getBalance() + "kr \n";

        }//ends if
    }//ends while
    return details;
}

public String bankAccounts() {
    String details = "ALL BANK ACCOUNTS" + "\n"
            + "-----------------" + '\n';

    if (accounts.size() == 0) {
        details += "There are no bank accounts";
    } else {
        Iterator iter = accounts.iterator();
        while (iter.hasNext()) {
            details += iter.next().toString() + '\n';
        }
    }
    return details;
}

@Override
public String toString() {

    return "Account " + accountNumber + ": " + owner
            + "\nBalance: " + balance + " kr.\n";
}

public Boolean authenticateUser(String login, String ssn) {
    if (Luhn.checkLogin(ssn)) {
        System.out.println("User authenticated");
        return true;
    } else {
        System.out.println("Authentication refused");
        return false;
    }
}

public void addAccAr(Account myAccount) {
    myAccounts.add(myAccount);
}


public Long getBalanceToLong() {
    long balTemp = balans;
    return balTemp;
}

public Long getPnTorLong() {

    return persnr;
}

public Long getAccNoLong() {

    long accTemp = accountNumber;
    return accTemp;
}

public ArrayList<Long> getAllAccounts() {
    ArrayList<Long> allAccounts = new ArrayList<>();
    System.out.println("ALL ACCOUNTS\n-----------");
    for (Account myAccount : myAccounts) {
        allAccounts.add(myAccount.getAccNoLong());
        allAccounts.add(myAccount.getPnTorLong());
        allAccounts.add(myAccount.getBalanceToLong());
    }
    return allAccounts;

}
/*
 public ArrayList<String> getMyAccounts() {
 ArrayList<String> ownAccounts = new ArrayList<>();
 System.out.println("MY ACCOUNTS\n-----------");
 for (Account myAccount : myAccounts) {
 ownAccounts.add(myAccount.getAccNoStr());
 ownAccounts.add(myAccount.getBalanceToStr());
 }
 return ownAccounts;

 }*/
}

This is our Customer class

package bank6;

import java.util.ArrayList;


public class Customer {
 int custCounter;

//attribut
private Long socialNo;
private String name;
private ArrayList customers;
public Integer customerNumber;
static Integer custNo = 1;

private ArrayList<Customer> clients = new ArrayList<Customer>();
//konstruktor

public Customer(String socialStr, String name) {
    Long socialTemp = new Long(socialStr);
    this.name = name;
    this.socialNo = socialTemp;
    customerNumber = custNo++;

}//ends  konstruktor customer6

public Customer() {
    customers = new ArrayList();
}

/* Set methods*/
public void setName(String name) {
    this.name = name;
}

public void setsocialNo(Long socialNo) {
    this.socialNo = socialNo;
}

/* get methods */
public String getName() {
    return name;
}

public String getSocialNoStr() {
    String socialTemp = Long.toString(socialNo);
    return socialTemp;
}

public Long getSocialNo() {
    return socialNo;
}

/*toString() method*/
@Override
public String toString() {

    return "\n" + "Owner: " + name + " (" + socialNo + ")";
}

public void addAccCustAr() {

}

public void addCustomerAr(Customer client) {
    clients.add(client);
}

public ArrayList<String> getAllClients() {
    ArrayList<String> allClients = new ArrayList<>();
    System.out.println("ALL CLIENTS\n-----------");
    for (Customer client : clients) {
        allClients.add(client.getName());
        allClients.add(client.getSocialNoStr() + "\n");
    }
    return allClients;
    //add account
    //public void addAccount(account6 account){
    //    accounts.add(account);
    //}// ends adds account
    //remove account
    //public void removeAccount (account6 account) {
    //    accounts.remove(account);
    //}//ends remove account
}
}//ends public class

This is our Luhn class

package bank6;

public class Luhn {

public static boolean checkLogin(String pnr) {

    if (pnr.length() != 10) {
        System.out.println("");
        return false;
    } else {

        int length = pnr.length();

        int sum = 0;
        int pos = length - 1;
        for (int i = 1; i <= length; i++, pos--) {

            char tmp = pnr.charAt(pos);
            int num = Integer.parseInt(String.valueOf(tmp));

            int produkt;
            if (i % 2 != 0) {
                produkt = num * 1;
            } else {
                produkt = num * 2;
            }
            if (produkt > 9) {
                produkt -= 9;
            }
            sum += produkt;
        }

        boolean korrekt = (sum % 10) == 0;

        if (korrekt) {
            System.out.println("Correct");
            return true;
        } else {
            System.out.println("Invalid");
            return false;
        }
    }
}
}
Artjom B.
  • 58,311
  • 24
  • 111
  • 196
Henrik
  • 23
  • 4

1 Answers1

1
  • Your Account class already has a Customer field -- good.
  • You should give Customer an ArrayList<Account> accounts field.
  • And also give Customer addAccount(Account acct) and removeAccount(Account acct) methods.
  • Why does Customer have an ArrayList<Customer> field? That makes little sense. Should a Customer hold a list of other Customers? Why? For what purpose?
  • Why does Account have private ArrayList<Account> myAccounts = new ArrayList<Account>();? That also makes little sense. Should an Account hold a bunch of other Accounts? Again, for what purpose?
  • The Account class should logically represent one and only one Account.
  • Same for the Customer class -- it should logically represent only one Customer.

If you think through things logically, they usually come together, and each component of your code should make sense. If it doesn't, question why it is there.

So this code is broken:

Account bank = new Account();

//....

bank.addNewAccount(cust1);
bank.addNewAccount(cust2);
bank.addNewAccount(cust3);

Since you're adding a bunch of Customer's to an Account object. It looks like you should have another class, a Bank class, one that can hold an ArrayList<Customer>. Wouldn't this make sense?

Hovercraft Full Of Eels
  • 276,051
  • 23
  • 238
  • 346