Java Reference
In-Depth Information
// Now output the results
for(int i = 0 ; i < accounts.length ; ++i) {
System.out.println("Account Number:"+accounts[i].getAccountNumber()
+ "\n" +
"Original balance
: $" + initialBalance[i] + "\n" +
"Total credits
: $" + totalCredits[i] + "\n" +
"Total debits
: $" + totalDebits[i] + "\n" +
"Final balance
: $" + accounts[i].getBalance() + "\n" +
"Should be
: $" + (initialBalance[i]
+ totalCredits[i]
- totalDebits[i]) + "\n");
}
Directory "BankOperation 3 - Multiple Accounts"
This is much the same as before except that you now extract values from the arrays you have created. If
you run this version it works perfectly, of course. A typical set of results is:
Account Number:1
Original balance : $500
Total credits : $659
Total debits : $614
Final balance : $545
Should be : $545
Account Number:2
Original balance : $800
Total credits : $607
Total debits : $306
Final balance : $1101
Should be : $1101
How It Works
You now allocate arrays for the initial account balances, the totals of credits and debits for each account,
and for the accounts themselves. The number of initializing values in the initialBalance[] array de-
termines the number of elements in each of the arrays. In the for loop, you create each of the accounts
with the appropriate initial balance and initialize the totalCredits[] and totalDebits[] arrays to
zero.
In the modified transactions loop, you select the account from the array for both the debit and the credit
transactions by generating a random index value that you store in the variable select . The index select
is also used to keep a tally of the total of the transactions of each type.
This is all well and good, but by declaring the methods in the class Bank as synchronized , you're limit-
ing the program quite significantly. No operation of any kind can be carried out while any other operation
is in progress. This is unnecessarily restrictive because there's no reason to prevent a transaction on one
account while a transaction for a different account is in progress. What you really want to do is constrain
Search WWH ::




Custom Search