Exercise 2: Creating a Test Program (Level 3)
In this exercise, you create a test harness (a test class) to exercise a pre-built class. These are the Level 3 instructions which provide additional hints with code snippets.
Task 1 - Creating the TestAccount
Class
Using a text editor, create the TestAccount
file. This class acts as a program to create an Account
object with an initial balance of 100. The test program will then deposit 50
and then withdraw 147. Finally, the test program must print out the balance of the class to the standard output stream.
Perform the following:
- Declare the
TestAccount
class.
public class TestAccount {
//code here
}
- Add the
main
method:
public class TestAccount {
public static void main(String[] args) {
//code here
}
}
- Declare a variable of type
Account
and initialize that variable by creating an instance of the Account
class with an initial balance of 100.
Account acct = new Account(100.0);
- Use the
deposit
method to add 50 to the account.
acct.deposit(50.0);
- Use the
withdraw
method to subtract 147 from the account.
acct.withdraw(147.0);
- Use the
getBalance
method to retrieve the new accoutn balance and use the System.out.println
method to display the balance to the standard output stream.
System.out.println("Final account balance is " + acct.getBalance());
Task 2 - Compiling the TestAccount
Program
On the command line, use the javac command to compile the test program.
javac TestAccount.java
Task 3 - Runnig th TestAccount
Program
On the command line, use java command to run the test program.
java TestAccount
The output should be:
The final balance is 3.0