简体   繁体   中英

Accessing hashmap value from another class

I'm having trouble trying to figure out my closeAccount() function in the Bank class. I have two parameters that i'm passing through. I need to search through my bank hashmap that contains both of these parameters and to close this specific account.

My Customer class holds a collection of Account objects, and the accountNumber is stored in the account class as a instance field.

I've got the first part where I use the containsKey() method to search the hashmap for my customerID parameter, but I can't figure out how to access the accountNumber parameter.

Customer.java

public class Customer {

    private String firstName;
    private String lastName;
    private String passcode;
    private int age;
    private String customerID;
    private ArrayList<Account> accounts;


    public Customer() {
        super();
    }


    public Customer(String firstName, String lastName, String passcode, int age, String customerID) {
        super();
        setFirstName(firstName);
        setLastName(lastName);
        setPasscode(passcode);
        setAge(age);
        setCustomerID(customerID);
        accounts = new ArrayList<>();
    }


    public ArrayList<Account> getStringList() {
        return accounts;
    }

    public void setStringList(ArrayList<Account> accounts) {
        this.accounts = accounts;
    }

    public String getFirstName() {
        return firstName;
    }


    public void setFirstName(String firstName) {
        if (firstName != null && !firstName.trim().isEmpty()) {
            this.firstName = firstName;
        }
    }


    public String getLastName() {
        return lastName;
    }


    public void setLastName(String lastName) {
        if (lastName != null && !lastName.trim().isEmpty()) {
            this.lastName = lastName;
        }
    }


    public String getPasscode() {
        return passcode;
    }

    public void setPasscode(String passcode) {

        if (passcode != null && !passcode.trim().isEmpty()) {
            this.passcode = passcode;
        }
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getCustomerID() {
        return customerID;
    }

    public void setCustomerID(String customerID){
        this.customerID = customerID;
    }

    //toString()

}

Bank.java

public class Bank {

    public static HashMap<String, Customer> theBank;


    public Bank() {
        super();
        theBank = new HashMap<>();
    }


    public void addCustomer(Customer newCustomer) {
        if (newCustomer != null) {
            theBank.put(newCustomer.getCustomerID(), newCustomer);
        }
    }


    public void closeAccount(String customerID, String accountNumber) {

        if (theBank.containsKey(customerID) && // theBank.containsValue(accountNumber)) {
            //theBank.remove(customerID, )
        }
    }


    public static void displayCustomerInformation(Customer customer){
        if(customer != null){
            System.out.println(customer);
        }
    }


    public static void displayAllCustomers(){
        for(Customer customer : theBank.values()){
            System.out.println(customer);

        }
    }

}

Account.java

public class Account {

    private String accountNumber;
    private double balance;
    private boolean active;
    private ArrayList<String> transactionInfo;

    public Account() {
        super();
    }


    public Account(String accountNumber, double balance) {
        super();
        if(accountNumber != null) {
            this.accountNumber = accountNumber;
        }

        setBalance(balance);
        active = true;
        transactionInfo = new ArrayList<String>();
    }


    public String getAccountNumber() {
        return accountNumber;
    }


    public double getBalance() {
        return balance;
    }


    public boolean isActive() {
        return active;
    }


    public void setBalance(double balance) {
        if(balance >= 0){
            this.balance = balance;
        }
    }


    public void setActive(boolean active) {
        this.active = active;
    }


    public void addToBalance(double amount) {
        if (amount > 0) {
            balance += amount;
        }
    }


    public void subtractFromBalance(double amount) {
        if (amount > 0) {
            balance -= amount;
        }
    }

    public void addTransactionInfo(String info) {
            if(info != null) {
                transactionInfo.add(info);
            }
    }

    public void displayAccountRecords() {
        if(transactionInfo != null) {
            for(String info: transactionInfo) {
                System.out.println(info);
            }
        }
    }

SavingsAccount.java

import java.util.ArrayList;

public class SavingsAccount extends Account {

    private final double MIN_AMOUNT = 50.0;

    public SavingsAccount() {
        super();
    }

    public SavingsAccount(String accountNumber, double balance) {
        super(accountNumber, balance);

        if(balance < MIN_AMOUNT) {
            setActive(false);
        } else {
            setActive(true);
        }
    }

    public double getMIN_AMOUNT() {
        return MIN_AMOUNT;
    }

}

ChequingAccount.java

public class ChequingAccount extends Account {

    private final double FEE = 0.25;
    private int numberOfCheques;

    public ChequingAccount() {
        super();
    }

    public ChequingAccount(String accountNumber, double balance, int numberOfCheques) {
        super(accountNumber, balance);
        setNumberOfCheques(numberOfCheques);
    }

    public double getFEE() {
        return FEE;
    }

    public int getNumberOfCheques() {
        return numberOfCheques;
    }

    public void setNumberOfCheques(int numberOfCheques) {
        if(numberOfCheques > 0) {
            this.numberOfCheques = numberOfCheques;
            subtractFromBalance(FEE);
        } else {
            System.out.println("Entered an invalid number of cheques");
        }
    }
}

GoldAccount.java

public class GoldAccount extends Account{

    private double interestRate;
    private boolean inOverdraft;
    private final double FEE = 0.50;
    private final double OVERDRAFT_AMT = -1000.0;

    public GoldAccount() {
        super();
    }

    public GoldAccount(String accountNumber, double balance, double interestRate, boolean inOverdraft) {
        super(accountNumber, balance);
        setInterestRate(interestRate);
        setInOverdraft(inOverdraft);

        if(balance < 0.0) {
            setInOverdraft(true);
            balance -= FEE;
        } else {
            setInOverdraft(false);
        }

    }

    public double getInterestRate() {
        return interestRate;
    }

    public void setInterestRate(double interestRate) {
        this.interestRate = interestRate;
    }

    public boolean isInOverdraft() {
        return inOverdraft;
    }

    public void setInOverdraft(boolean inOverdraft) {
        this.inOverdraft = inOverdraft;
    }

}

All you should need to do is check to make sure the customer is in the system, access them, and remove the specified account number from their account list:

if (theBank.contains(customerID)) {
    theBank.get(customerID).remove(accountNumber);
}

With Java8 stream

...

public void closeAccount(String customerID, String accountNumber) {

    if (theBank.containsKey(customerID)) {
        theBank.get(customerID).setStringList( 
           theBank.get(customerID).getStringList().stream()
                .filter(a -> !a.getAccountNumber.equals(accountNumber))
                .collect(Collectors.toCollection(ArrayList::new)));
    }
}
...

You need to find the customer then iterate over it's accounts to match the account number.

I delegated the removeAccount action to the Customer class.

public boolean closeAccount(String customerID, String accountNumber) {
    Customer c = theBank.get(customerID);
    if (c != null) {
        return c.removeAccount(accountNumber);
    }
    return false;
}

So that the Customer object is aware it has one less account.

The Customer class will search for the correct account and then remove it.

public Account getAccount(String acctNum) {
    for(Account a: accounts) {
        if(acctNum.equals(a.getAccountNumber())) {
            return a;
        }
    }
    return null;
}

public boolean removeAccount(String acctNum) {
    Account a = getAccount(acctNum);
    if(a != null) {
        a.setActive(false);
        accounts.remove(a);
        return true;
    }
    return false;
}

There is a boolean return value to check if it was removed.

This is complete code (minus unused getters/setters).

import java.util.*; // for convenience only

public class BankTest {
    public static void main(String[] args) {

        Bank b = new Bank();
        Customer c = new Customer("john", "doe", "1234", 25, "foobar");
        c.getStringList().add(new Account("54321", 100));

        b.addCustomer(c);
        b.displayAllCustomers();
        if(b.closeAccount("foobar", "54321")) {
            System.out.println("account closed");
        }
        System.out.println("*** after close");
        b.displayAllCustomers();
    }
}

class Customer {

    private String firstName;
    private String lastName;
    private String passcode;
    private int age;
    private String customerID;
    private ArrayList<Account> accounts = new ArrayList<>();

    public Customer(String firstName, String lastName, String passcode, int age, String customerID) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.passcode = passcode;
        this.age = age;
        this.customerID = customerID;
    }

    public Account getAccount(String acctNum) {
        for(Account a: accounts) {
            if(acctNum.equals(a.getAccountNumber())) {
                return a;
            }
        }
        return null;
    }

    public boolean removeAccount(String acctNum) {
        Account a = getAccount(acctNum);
        if(a != null) {
            a.setActive(false);
            accounts.remove(a);
            return true;
        }
        return false;
    }

    public List<Account> getStringList() {
        return accounts;
    }

    public String getCustomerID() {
        return customerID;
    }

    @Override
    public String toString() {
        return "Customer{"+firstName+" "+lastName+" - id:"+customerID+" accounts:"+accounts.size()+"}";
    }
}

class Bank {

    public static HashMap<String, Customer> theBank = new HashMap<>();

    public void addCustomer(Customer newCustomer) {
        if (newCustomer != null) {
            theBank.put(newCustomer.getCustomerID(), newCustomer);
        }
    }

    public boolean closeAccount(String customerID, String accountNumber) {
        Customer c = theBank.get(customerID);
        if (c != null) {
            return c.removeAccount(accountNumber);
        }
        return false;
    }

    public static void displayCustomerInformation(Customer customer){
        System.out.println(customer);
    }

    public static void displayAllCustomers(){
        for(Customer customer : theBank.values()){
            System.out.println(customer);
            customer.getStringList().forEach(acc -> System.out.println(acc));
        }
    }
}

class Account {

    private String accountNumber;
    private double balance;
    private boolean active;
    private ArrayList<String> transactionInfo = new ArrayList<>();

    public Account(String accountNumber, double balance) {
        this.accountNumber = accountNumber;
        this.balance = balance;
        this.active = true;
    }

    public String getAccountNumber() {
        return accountNumber;
    }

    public double getBalance() {
        return balance;
    }

    public boolean isActive() {
        return active;
    }

    public void setActive(boolean active) {
        this.active = active;
    }


    @Override
    public String toString() {
        return "Account{"+accountNumber+" "+balance+"}";
    }
}

A simpler way
This uses your code as it would be this. You need to get the customer and then iterate over the list of accounts to find the required account and then do whatever you want with it.

public boolean closeAccount(String customerID, String accountNumber) {

    Customer c = theBank.get(customerID);

    if(c != null) {
        for (Account a: c.getStringList()) {
            if(accountNumber.equals(a.getAccountNumber())) {
                // do whatever you need to to deactivate the account here.
                return true;
            }
        }
    }
    return false;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM