Next: Constructor methods. Up: Defining an object. Previous: The Account class.


Using Account

A one-account bank

Using the Account class we've defined, we can now put together a complete program using this Account object we created. We're going to create an additional class called VerySimpleBank - to allow us to work with a bank for which there is only one account. This class would be placed into a separate file, called VerySimpleBank.java.

import csbsju.cs160.*;

public class VerySimpleBank {
    public static void run() {
        Account mine = new Account();
        while(true) {
            IO.print("Balance: ");
            IO.println(mine.getBalance());
            IO.print("Deposit? ");
            mine.deposit(IO.readDouble());
        }
    }
}

A more complex bank

A one-account bank isn't very realistic. Instead, let's make a program that works with two accounts!

import csbsju.cs160.*;

public class SimpleBank {
    public static void run() {
        Account mine = new Account();
        Account yours = new Account();
        while(true) {
            Account a;
            IO.print("Which account? ");
            if(IO.readInt() == 0) a = mine;
            else                  a = yours;

            IO.print("Balance: ");
            IO.println(a.getBalance());
            IO.print("Deposit? ");
            a.deposit(IO.readDouble());
        }
    }
}
In this program, we've added a new account (yours). And we've added some code at the beginning of the loop, allowing the user to choose which account to work with in that iteration.

If we ran this program, we'd see the following.

Which account? 0       we select my account
Balance: 0.0             my account has $0 so far
Deposit? 5000
Which account? 1       we select your account
Balance: 0.0             your account has $0 so far
Deposit? 3
Which account? 0       we select my account
Balance: 5000.0          my account has $5000 so far
 : and so on


Next: Constructor methods. Up: Defining an object. Previous: The Account class.