In main I do this:
First I create a new customer with its first name, lastname and number.
Then I create two savingsAccounts, with its amount, id and interest rate.
I then add the two savingsAccounts to the new customer.
Finally I add the new customer to the bank.
Customer newCustomer = new Customer(firstName, lastName, pnumber);
SavingsAccount savingsAccount1 = new SavingsAccount(400, "1", 4); //400$ into account no.1, with interest 4%
SavingsAccount savingsAccount2 = new SavingsAccount(300, "2", 3);
newCustomer.addAccount(savingsAccount1);
newCustomer.addAccount(savingsAccount2);
bank.addCustomer(newCustomer);
Here is class Bank:
public class Bank {
String bankName;
private ArrayList<Customer> customers = new ArrayList<Customer>();
Bank(String bankName) {
this.bankName = bankName;
}
public void addCustomer(Customer newCustomer) {
customers.add(newCustomer);
}
}
Here is class Customer:
public class Customer {
private String firstName;
private String lastName;
private String number;
private ArrayList<Account> accounts;
Customer(String firstName, String lastName, String number) {
this.firstName = firstName;
this.lastName = lastName;
this.number = number;
this.accounts = new ArrayList<Account>();
}
public void addAccount(SavingsAccount account) {
accounts.add(account);
}
public void addAccount(CreditAccount account) {
accounts.add(account);
}
public ArrayList<Account> getAccounts() {
return accounts;
}
}
Here is class SavingsAccount (that inherits class Account):
public class SavingsAccount extends Account {
public SavingsAccount() {
super();
}
public SavingsAccount(double bal, String id, double inte) {
super(bal, id, inte);
}
#Override
public void deposit(String number, String id, double amount) {
}
#Override
public void withdraw(String number, String id, double amount) {
}
#Override
public void transfer(String number, String id, double amount) {
}
#Override
public double getBalance() {
}
#Override
public String getAccountId() {
return accountId;
}
#Override
public double getInterest(){
return interest;
}
}
My problem is:
How can I write code in class SavingsAccount to deposit, withdraw, transfer money for a certain customer, for a certain account?
Let's say I want to deposit 500 to customer no.2 on his account no.1.
That should be something like savingsAccount.deposit("2", "1", 500);
I just can't figure out how to access customer number 2, and his account number 1.
Can anyone help me please?
What you could do is have a method for that in the Bank class:
public class Bank {
// Your stuff
// new method:
public boolean transfer(Account accountFrom, double amount, String nameTo, int account) {
//check if the balance can be deposit from the account
if(amount <= accountFrom.getBalance()) {
//Check if the person exists in the bank
String name = nameTo.split(" "); // name[0] is the first name, name[1] last name
boolean success = false;
for(Customer c: customers) {
if(c.getFirstName().equalsIgnoreCase(name[0]) &&
c.getLastName().equalsIgnoreCase(name[1]) {
for(Account a : c.getAccounts()) {
if(a.getAccountId() == account) {
// Add it to the account
a.deposit(amount);
success = true;
break;
}
}
break;
}
}
// Deposit it from the account (That class should only keep track of money, so it
// only takes an argument to deposit or withdraw a value, the rest is done by the bank
// Only do this if money has been dsposited at the target account
if(success){
accountFrom.withdraw(amount);
return true;
}
}
return false;
}
}
For this to happen you have to structurely change your setup.
Have the accounts only manage money, those accounts get added to a customer. The customer is the person who communicates between the bank and himself. And finally the bank communicates with customers.
I hope this will help you in the direction
Related
I have been stuck on this for more than 3 days now.
In my main class, ATM, in method verifyCustomer(). When signing in, I'm trying to find a way to ask for a customer ID first. Once verified, then the customers accounts will be listed. After that, the customer will then be prompted to choose which account they want to access, and from there they will be prompted to enter the account number and then the password.
I also have a Gold Account class in which only customers above a certain age "65" are allowed the option to open up. I am having trouble figuring out the logic on how to access that in the initialize() method as well.
I have 3 subclasses to the Account superclass which I didn't include due to there already being too much code.
Any tips?
ATM.java
public class ATM {
private InputReader reader;
private String accountNumber;
private String passcode;
private boolean customerVerified;
private String customerID;
private Bank theBank;
private Customer currentCustomer;
public ATM() {
super();
initialize();
run();
}
public static void main(String[] args) {
new ATM();
}
public void run() {
reader = new InputReader();
boolean exit = false;
while (!exit) {
System.out.println("Welcome to Bank");
System.out.println("Choose one of the following options");
System.out.println("1 - Sign In");
System.out.println("2 - Deposit");
System.out.println("3 - Withdraw");
System.out.println("4 - Display Account Info");
System.out.println("5 - Exit");
System.out.println(">");
int choice = reader.getIntInput();
switch (choice) {
case 1:
verifyCustomer();
break;
case 2:
transactDeposit();
break;
case 3:
transactWithdraw();
break;
case 4:
displayAccountInformation();
break;
case 5:
System.out.println("Thank you for banking at Bank");
System.exit(0);
}
}
}
public void initialize() {
Customer tom = new Customer("Tom", "Smith", "123",70,"A001");
Customer jane = new Customer("Jane", "Smith", "789",18,"A002");
Customer bob = new Customer("Bob", "Smith", "456",32,"A003");
Account tomChequing = new ChequingAccount("CH-123", 0.0,2);
Account tomSavings = new SavingsAccount("SA-123", 50.0);
Account tomGold = new GoldAccount("GL-123",50.0,2.0);
Account janeChequing = new ChequingAccount("CH-789",0.0,2);
Account janeSavings = new SavingsAccount("SA-789", 0.0);
Account bobChequings = new ChequingAccount("CH-456",0.0,5);
Account bobSavings = new SavingsAccount("SA-456", 100.0);
tom.addAccount(tomChequing);
tom.addAccount(tomSavings);
tom.addAccount(tomGold);
jane.addAccount(janeChequing);
jane.addAccount(janeSavings);
bob.addAccount(bobChequings);
bob.addAccount(bobSavings);
theBank = new Bank();
theBank.addCustomer(tom);
theBank.addCustomer(jane);
theBank.addCustomer(bob);
if(currentCustomer.getAge() >= 65) {
currentCustomer.
}
}
public void transactDeposit() {
if (customerVerified) {
System.out.println("Enter the amount to deposit: ");
currentCustomer.getAccountList().addToBalance(reader.getDoubleInput());
} else {
System.out.println("ERROR: You must LOGIN before you can perform a transaction.");
verifyCustomer();
}
}
public void transactWithdraw() {
if (customerVerified) {
System.out.println("Enter the amount to withdraw: ");
currentCustomer.getAccount().subtractFromBalance(reader.getDoubleInput());
} else {
System.out.println("ERROR: You must LOGIN before you can perform a transaction.");
verifyCustomer();
}
}
public void displayAccountInformation() {
if (customerVerified) {
System.out.println("Here is your information.");
System.out.println(currentCustomer.toString());
} else {
System.out.println("ERROR: You must LOGIN before you can perform a trasnsaction.");
verifyCustomer();
}
}
public void verifyCustomer() {
System.out.println("Enter your Customer ID");
customerID = reader.getStringInput();
System.out.println("Which account do you want to access?");
System.out.println("Enter Account Number: ");
accountNumber = reader.getStringInput();
System.out.println("Enter your passcode");
passcode = reader.getStringInput();
currentCustomer = Bank.theBank.get(accountNumber);
if (currentCustomer != null) {
if (passcode.equals(currentCustomer.getPasscode()) && customerID.equals(currentCustomer.getCustomerID())) {
customerVerified = true;
} else {
System.out.println("ERROR: Either account number, customer id, or passcode is not correct.");
run();
}
} else {
System.out.println("ERROR: Either account number, customer id, or passcode is not correct.");
run();
}
}
}
Customer.java
import java.util.ArrayList;
public class Customer {
private String firstName;
private String lastName;
private String passcode;
private int age;
private String customerID;
private ArrayList<Account> accounts;
public Customer(String firstName, String lastName, String passcode, int age, String customerID) {
setFirstName(firstName);
setLastName(lastName);
setPasscode(passcode);
setAge(age);
setCustomerID(customerID);
accounts = new ArrayList<>();
}
public void addAccount(Account account) {
accounts.add(account);
}
public ArrayList<Account> getAccountList() {
return accounts;
}
public void setAccountList(ArrayList<Account> account) {
this.accounts = account;
}
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;
}
}
Account.java
import java.util.ArrayList;
public class Account {
private String accountNumber;
private double balance;
private boolean active;
protected 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);
}
}
}
}
Bank.java
import java.util.HashMap;
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);
}
}
// use the customerID to access their collection of accounts
public void closeAccount(String customerID, String accountNumber) {
Customer c = theBank.get(customerID);
if(c != null) {
for(Account a: c.getAccountList()) {
if(accountNumber.equals(a.getAccountNumber())) {
theBank.remove(accountNumber);
}
}
//if (theBank.containsKey(customerID)) {
//theBank.get(customerID).getAccountList().remove(accountNumber);
}
}
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);
}
}
}
You have a HashMap in class Bank and the map key is customer ID. Just add a getCustomer(String) method in class Bank.
public Customer getCustomer(String id) {
return theBank.get(id);
}
Hello i tried to build a simple banking application now i want to write test case for withdraw deposit and transfer please help me in that here is the code
Account.java
public BigInteger getAccountNumber() {
return accountNumber;
}
public void setAccountNumber(BigInteger accountNumber) {
this.accountNumber = accountNumber;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getOwner() {
return ownerName;
}
public void setOwner(String owner) {
this.ownerName = owner;
}
public BigDecimal getBalance() {
return balance;
}
public BigDecimal setBalance(BigDecimal balance) {
this.balance = balance;
return balance;
}
Bank.java
package org.mybank.entities;
// Bank details.
public class Bank {
private String IFSC;
private Integer id;
private String address;
public String getIFSC() {
return IFSC;
}
public void setIFSC(String iFSC) {
IFSC = iFSC;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
chekings.java
package org.mybank.entities;
// checking account extending Account
public class Chekings extends Account {
private String checkingtype;
public String getCheckingtype() {
return checkingtype;
}
public void setCheckingtype(String checkingtype) {
this.checkingtype = checkingtype;
}
}
Savings
package org.mybank.entities;
// Savings account extending Account
public class Savings extends Account {
private String savingsType;
public String getSavingsType() {
return savingsType;
}
public void setSavingsType(String savingsType) {
this.savingsType = savingsType;
}
}
transaction.java
package org.mybank.entities;
import java.math.BigDecimal;
import java.math.BigInteger;
public class Transaction {
// main class
private BigDecimal amout;
private String transactionType;
private BigInteger sourceAccNum;
private BigInteger destAccNum;
private Integer transactionId;
}
Operations.java this is where iam performing testcases for withdraw deposit and transfer
package org.mybank.business;
import java.math.BigDecimal;
import java.math.BigInteger;
import org.mybank.entities.Account;
import org.mybank.entities.Savings;
public class Operations {
// withdraw specified amount from the specified account number
public void withdrawl(BigInteger accNum, BigDecimal amount) throws Exception {
Account acc = findAccount(accNum);
if (acc!=null) { // check if it is valid account
if (acc.getBalance().floatValue() >= amount.floatValue()) {
if (acc.getType().equals("SAVINGS")) { // if savings account.
Savings savingsAccount = getSavingsAccount(acc.getAccountNumber());
if (savingsAccount.getSavingsType().equals("INDIVIDUAL") && amount.floatValue() > 1000) {
throw new Exception("Idividual account cannot withdraw amount more than 1000.");
} else {
// create a transaction here
acc.setBalance(new BigDecimal(acc.getBalance().floatValue() - amount.floatValue()));
}
}
} else {
throw new Exception("Insufficient funds");
}
}else{
throw new Exception("Invalid Account");
}
}
//returns saving acc based on account number
private Savings getSavingsAccount(BigInteger accountNumber) {
return new Savings();
}
// returns account based on account number
private Account findAccount(BigInteger accNum) {
// TODO Auto-generated method stub
return new Account();
}
// transfers funds from source to destination.
public void transfer(BigInteger sourceAccNum, BigInteger destAccNum, BigDecimal amount) throws Exception {
Account src = findAccount(sourceAccNum);
Account dest = findAccount(destAccNum);
if(src!=null && dest!=null){
if(src.getBalance().floatValue()>amount.floatValue()){
// create a new trascation instance here
src.setBalance(new BigDecimal(src.getBalance().floatValue() - amount.floatValue()));
dest.setBalance(new BigDecimal(dest.getBalance().floatValue() + amount.floatValue()));
}else{
throw new Exception("Insufficient funds");
}
}else{
throw new Exception("Invalid account.");
}
}
// deposit amount in specified account.
public BigDecimal deposit(BigInteger accNum, BigDecimal amount) throws Exception {
Account acc = findAccount(accNum);
if(acc!=null){
// create a new trascation instance here
acc.setBalance(new BigDecimal(acc.getBalance().floatValue() + amount.floatValue()));
}else{
throw new Exception("Invalid Account");
}
return amount;
}
}
Here is the test code which i wrote . it always fails.if i use try catch block it was always passing the test help me in writing the perfect test code . this is my first time in writing test code in Junit.
import static org.junit.Assert.*;
import java.math.BigDecimal;
import java.math.BigInteger;
import org.junit.Test;
import org.mybank.business.Operations;
import junit.framework.Assert;
public class banking {
#Test
public void deposittest() throws Exception {
Operations optest = new Operations();
int a= 123;
Double b= (double) 2000;
BigDecimal result;
result = optest.deposit(BigInteger.valueOf(a),BigDecimal.valueOf(b));
assertEquals(2000,result);
}
}
The deposit method isn't setting the balance, it's adding to the existing balance. So the account had better have something already in the balance. At the very least, you can use an initializer in the declaration of the balance field:
class Account {
...
private BigDecimal balance = BigDecimal.valueOf(0);
...
}
You could also handle the initialization as part of a constructor.
I get this Exception when I try to create a new customer in my bank account program:
Exception in thread "main" java.lang.NullPointerException
at bank.program.Customer.addAccount(Customer.java:18)
at bank.program.BankProgram.main(BankProgram.java:24)
Java Result: 1
What does it mean, and what do I need to change to get rid of it?
Bank class:
public class Bank {
String bankName;
private ArrayList<Customer> customers = new ArrayList<Customer>();
Bank(String bankName) {
this.bankName = bankName;
}
public void addCustomer(Customer newCustomer) {
customers.add(newCustomer);
}
}
Account class:
public abstract class Account {
protected double balance = 0;
protected String accountId;
public Account() {} //Defaultkonstruktor
public Account(double bal, String id) { //Konstruktor
if (balance >= 0) {
balance = bal;
}
else {
balance = 0;
}
accountId = id;
}
public abstract void deposit(double amount);
public abstract void withdraw(double amount);
public abstract double getBalance();
public abstract String getAccountId();
public void transfer(double amount, Account account) {
account.deposit(amount);
balance -= amount;
}
}
SavingsAccount class:
public class SavingsAccount extends Account {
private double interest = 2.9;
public SavingsAccount() {
super();
}
public SavingsAccount(double bal, String id) {
super(bal, id);
}
#Override
public void deposit(double amount) {
}
#Override
public void withdraw(double amount) {
}
#Override
public double getBalance() {
}
#Override
public String getAccountId() {
}
}
Customer class:
public class Customer {
private String firstName;
private String lastName;
private String number;
private ArrayList<Account> accounts;
Customer(String firstName, String lastName, String number) {
this.firstName = firstName;
this.lastName = lastName;
this.number = number;
}
public void addAccount(SavingsAccount account) {
accounts.add(account);
}
public ArrayList<Account> getAccounts() {
return accounts;
}
}
Bank program class:
public class BankProgram {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int numberOfCustomers = 0;
Bank bank = new Bank("Bank name");
System.out.print("Enter amount to deposit: ");
double amount = input.nextDouble();
System.out.println("Account number: " + numberOfCustomers);
System.out.print("First name: ");
String firstName = input.next();
System.out.print("Last name: ");
String lastName = input.next();
System.out.print("Customer number: ");
String pnumber = input.next();
Customer newCustomer = new Customer(firstName, lastName, pnumber);
SavingsAccount savingsAccount = new SavingsAccount(amount, "11");
newCustomer.addAccount(savingsAccount);
bank.addCustomer(newCustomer);
}
}
You're trying to add an account without initializing the ArrayList in which they're stored. Add this to your Customer constructor.
this.accounts = new ArrayList<Account>();
In your Customer class, you declare an ArrayList accounts. Then, you have a method called addAccount, but it seems as though this accounts was never initialized.
Somewhere where you create your Customer object, you need to say:
newCustomer.accounts = new ArrayList<Account>();
I'm creating a java project named Bank. SavingsAccount and CurrentAccount classes are subclasses of Account class. In a class Bank, which stores an information about accounts I have to create a method which prints the sum of balance amount for all SAVINGS accounts. How should I write the method to sum exactly a balance of savings accounts, not of both savings and current accounts?
import java.util.ArrayList;
public class Bank
{
private ArrayList<Account> accounts;
public Bank()
{
super();
accounts = new ArrayList<Account>();
}
public void addAccount(Account theAccount)
{
accounts.add(theAccount);
}
public void getDescription()
{
for(Account account: accounts)
{
System.out.println("Name: " + account.getOwnerName() + "\nCode: " + account.getCode() + "\nBalance: " + account.getBalance());
}
}
public double accountsSum()
{
double total = 0;
for(Account acc: accounts)
{
total += acc.getBalance();
}
return total;
}
public void printSavingsBalance()
{
//?????
}
}
public class Account
{
protected String code;
protected String ownerName;
protected double balance;
public Account(String code,String ownerName, double balance)
{
this.code = code;
this.ownerName = ownerName;
this.balance = balance;
}
public String getCode(){return code;}
public String getOwnerName(){return ownerName;}
public double getBalance(){return balance;}
public void setBalance(double newBalance)
{
balance = newBalance;
}
public void addMoney(double plusMoney)
{
balance += plusMoney;
}
public void withdrawMoney(double minusMoney)
{
balance -= minusMoney;
}
}
public class SavingsAccount extends Account
{
private int term;
private double interestRate;
public SavingsAccount(int term, double interestRate, String code, String ownerName, double balance)
{
super(code,ownerName,balance);
this.term = term;
this.interestRate = interestRate;
}
public int getTerm(){return term;}
public double getInterestRate(){return interestRate;}
public void setTerm(int newTerm)
{
term = newTerm;
}
public void setInterestRate(double newInterestRate)
{
interestRate = newInterestRate;
}
public double interestSize()
{
return balance*interestRate/365*term;
}
}
You can use the instanceof to determine the type of the object and sum only when the type is Savings.
int totalBalance = 0;
for(Account account: accounts){
if (account instanceof Saving) {
totalBalance = totalBalance + account.getBalance();
}
}
private List<SavingsAccount> savingsAccounts;
private List<CurrentAccount> currentAccounts;
public addAccount(SavingsAccount account){
}
public addAccount(CurrentAccount account){
}
This would be much better to do. Then just iterate over the savings accounts and add the balance of all accounts. Introducing accountType and instanceof checks would be against polymorphism IMHO.
A much cleaner approach with Visitor pattern:
public class Bank{
private List<Account> accounts = new ArrayList<Account>();
public void add(Account account) {
accounts.add(account);
}
public double getBalance(){
AdditionAccountVisitor visitor = new AdditionAccountVisitor();
for(Account account : accounts){
account.accept(visitor);
}
return visitor.getSum();
}
}
abstract class Account{
private double balance;
public Account(double balance) {
this.balance = balance;
}
public double getBalance(){
return balance;
}
public abstract void accept(AccountVisitor visitor);
}
class SavingsAccount extends Account{
public SavingsAccount(double balance) {
super(balance);
}
#Override
public void accept(AccountVisitor visitor) {
visitor.visit(this);
}
}
class CurrentAccount extends Account{
public CurrentAccount(double balance) {
super(balance);
}
#Override
public void accept(AccountVisitor visitor) {
visitor.visit(this);
}
}
interface AccountVisitor{
public void visit(SavingsAccount savingsAccount);
public void visit(CurrentAccount savingsAccount);
}
class AdditionAccountVisitor implements AccountVisitor{
private double sum = 0.0;
#Override
public void visit(SavingsAccount savingsAccount) {
sum += savingsAccount.getBalance();
}
#Override
public void visit(CurrentAccount savingsAccount) {
//do nothing
}
public double getSum(){
return sum;
}
}
add an accountType field to the Account class, possibly of type enumeration (but also int etc). Then in the loop check if the account is of the desired type before adding the balance.
public void printSavingsBalance()
{
double total = 0;
for(Account acc: accounts)
{
if (acc.getType() == SAVINGS)
total += acc.getBalance();
}
return total;
}
or use 2 lists as suggested by #Narendra Pathai - depends on what else you want to do with the accounts and list
If you're emotionally distraught at the thought of using instanceof, add a virtual method to your superclass and define it thusly in each subclass:
Savings:
String accountType() {
return "Savings";
}
Checking:
String accountType() {
return "Checking";
}
I just have what I'm sure is a very easy and quick question here... So let's say I have an Account class as follows:
import java.text.NumberFormat;
public class Account
{
private final double RATE = 0.03; // interest rate of 3.5%
private long acctNumber;
private double balance;
private String name;
//-----------------------------------------------------------------
// Sets up the account by defining its owner, account number,
// and initial balance.
//-----------------------------------------------------------------
public Account (String owner, long account, double initial)
{
name = owner;
acctNumber = account;
balance = initial;
}
//-----------------------------------------------------------------
// Deposits the specified amount into the account. Returns the
// new balance.
//-----------------------------------------------------------------
public double deposit (double amount)
{
balance = balance + amount;
return balance;
}
//-----------------------------------------------------------------
// Withdraws the specified amount from the account and applies
// the fee. Returns the new balance.
//-----------------------------------------------------------------
public double withdraw (double amount, double fee)
{
balance = balance - amount - fee;
return balance;
}
//-----------------------------------------------------------------
// Adds interest to the account and returns the new balance.
//-----------------------------------------------------------------
public double addInterest ()
{
balance += (balance * RATE);
return balance;
}
//-----------------------------------------------------------------
// Returns the current balance of the account.
//-----------------------------------------------------------------
public double getBalance ()
{
return balance;
}
//-----------------------------------------------------------------
// Returns a one-line description of the account as a string.
//-----------------------------------------------------------------
public String toString ()
{
NumberFormat fmt = NumberFormat.getCurrencyInstance();
return acctNumber + "\t" + name + "\t" + fmt.format(balance);
}
}
And I create the Bank class shown here...
public class Bank
{
Account[] accounts;// = new Account[30];
int count=0;
String name;
public Bank(String name)
{
this.name = name;
accounts = new Account[30];
}
public void addAccount(Account acct)
{
accounts[count] = acct;
count++;
}
public void addInterest()
{
//for (Account acct : accounts)
//acct.addInterest();
for(int i = 0; i < count; i++)
accounts[i].addInterest();
}
}
I receive an error if I try to use the addInterest() method with the
for (Account acct: accounts) loop you see commented out. Can someone please provide me with insight on why this is? I thought these loops were equivalent. Thanks in advance.
The for loop over an iterable array iterates all 30 elements, not only the elements you really added.
You may use an ArrayList<Account> and add elements as needed. This allows you to omit the count field:
public class Bank
{
ArrayList<Account> accounts = new ArrayList<Account>();
String name;
public Bank(String name)
{
this.name = name;
}
public void addAccount(Account acct)
{
accounts.add(acct);
}
public void addInterest()
{
for (Account acct : accounts)
acct.addInterest();
}
}
You have to initialize the Account array
so you might want to change this to:
public void addInterest()
{
//for (Account acct : accounts)
//acct.addInterest();
for(int i = 0; i < count; i++)
accounts[i].addInterest();
}
to something like this:
public void addInterest()
{
for (Account acct : accounts) {
acct= new Account("John",1234596069,200.00);
acct.addInterest();
}
// for(int i = 0; i < count; i++)
// accounts[i].addInterest();
}
Essentially you have to initialize the array variable before invoking a method.