Java Reference
In-Depth Information
}
clerk1.doTransaction(transaction); // Now do the credit
// choose an account at random for debit operation
select = rand.nextInt(accounts.length);
amount = 30 + rand.nextInt(31); // Generate amount of $30 to $60
transaction = new Transaction(accounts[select], // Account
Transaction.DEBIT, // Debit transaction
amount); // of amount
totalDebits[select] += amount; // Keep total debit tally
// Wait until the second clerk is free
while(clerk2.isBusy()) {
try {
Thread.sleep(25); // Busy so try later
} catch(InterruptedException e) {
System.out.println(e);
}
}
clerk2.doTransaction(transaction); // Now do the debit
}
The last modification we must make to the method main() is for outputting the results. We now do this
in a loop seeing as we have to process more than one account:
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");
This is much the same as before except that we now extract values from the arrays we have created. If
you run this version it will, of course, work perfectly. 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
Search WWH ::




Custom Search