/*********************************************** * CS2510 Fall 2011 * Lecture #18_1 * ArrayList, While Loops, Traversal, Static ***********************************************/ // Get the ArrayList from the java libraries import java.util.ArrayList; import tester.*; // Represents a Checking account (A group of them actually) class Checking{ // Number of checking accounts we've created static int numaccounts = 0; // A list of the accounts we've created static ArrayList accounts = new ArrayList(); // The balance for an account double balance; // Sets the balance and adds to our global counters Checking(double balance) { this.balance = balance; numaccounts = numaccounts + 1; accounts.add(this); } // Returns the total number of accounts created static int getNumAccounts() { return numaccounts; } // Gets the sum of the balances of all accounts in the bank static double getBankBalance() { Traversal travis = new Traversal(accounts); double total = 0; while (! travis.isEmpty()) { total = total + travis.first().balance; travis.rest(); } return total; } // Gets the sum of the balances of all accounts in the bank /* static double getBankBalance() { double total = 0; int index = 0; while (index < accounts.size()) { total = total + accounts.get(index).balance; index = index + 1; } return total; } */ } // A class to Traverse a list (make an arraylist look like a linked list) class Traversal { int index; ArrayList list; Traversal(ArrayList list) { this.list = list; index=0; } Traversal(ArrayList list, int index) { this.list = list; this.index = index; } // Give me the element at this position in the traversal X first() { return list.get(index); } /* Traversal rest() { return new Traversal(list,index + 1); } */ // Go to the next element void rest() { index = index + 1; } // Are we at the end of our list? boolean isEmpty() { return index >= list.size(); } } // Some examples of checking accounts class BankExamples { Checking c1 = new Checking(20.0); Checking c2 = new Checking(25.0); Checking c3 = new Checking(10.0); // Tests of our static methods void testChecking(Tester t) { t.checkExpect(Checking.numaccounts,3); t.checkExpect(Checking.getBankBalance(),55.0); } }