public class Account{

//class properties/attributes

private String custId;

private double balance;

//constructor method

public Account(String custId){

this.custId = custId;

this.balance = 0;

}

//another constructor method (method overloading)

public Account(String custId, double balance){

this.custId = custId;

this.balance = balance;

}

//accessor methods

public String getID(){

return this.custId;

}

public double getBalance(){

return this.balance;

}

//mutator methods

public void setBalance(int newBalance){

this.balance = newBalance;

}

}

Suggested Solution

Task 1 Part A

Start a new Project and create the Account class. Click the button to access the code.

Task 1 Part B

In your main class, create an array with an identifier accounts of 10 Account objects.

Use the following code to analyse the current contents of the array. What do you see?

for(int i = 0; i<accounts.length; i++){

System.out.println(accounts[i]);

}

Task 1 Part C

Assign a new Account object to a few of the elements in the array eg:

accounts[3] = new Account("ac-101");

accounts[5] = new Account("ac-102", 1000);

Note: the Account class has two constructor methods which behave differently. They have different parameter lists. This is an example of method overloading!

Again, use a loop to analyse the contents of the array. What do you see?

for(int i = 0; i<accounts.length; i++){

System.out.println(accounts[i]);

}

Hopefully you will now see something like Account@7344699f

This represents the memory address of a reference variable to an Account object in memory, eg accounts[3].

You can see in the above diagram that accounts is a reference to an array of Account objects and accounts[0] is a reference to a single Account object, or null...

Task 1 Part D

Adapt your loop code so that the id of every Account in the array is displayed ie:

for(int i = 0; i<accounts.length; i++){

System.out.println(accounts[i].getID());

}

What happens?

If you don't have an Account object at index 0, assign one to accounts[0] and run your code again.

You can see that the compiler attempts to run the program and it is able to display the id of the Account at index 0.

However, when it reaches an index which references null, the program crashes. This is a RUNTIME ERROR!

Task 1 Part E

FIX THE RUNTIME ERROR!

Task 1 Part F

This question is designed for students who are serious about getting a 4 or 5 in AP Computer Science or a 6 or 7 in IB Computer Science.

Design a static helper method in your Main class which will process the accounts array. It will use the Selection Sort algorithm to sort the array into ascending order of balance.

pre-condition: the array may have any number of nulls

Test your design.

You may want to design another static method which will display the balance of every account after the sorting has been completed.