Question: Modify class Account (Fig. 3.13) to provide a method called debit that withdraws money from an Account. Ensure that the debit amount does not exceed the Account’s balance. If it does, the balance should be left unchanged and the method should print a message indicating “Debit amount exceeded account balance.” Modify class AccountTest (Fig. 3.14) to test method debit.
To run the application save both files with the same name as the class (because it is a public class) and with the .java file extension (in this case Ex03_12.java and Ex03_12_Test.java). Then compile both classes and run Ex03_12_Test. Ex03_12 will not run because it does not have a main method.
To compile both classes at the same time using the command prompt, use the command
javac Ex03_12.java Ex03_12_Test.java
To run Ex03_12_Test, use the command
java Ex03_12_Test
1 2 |
/**<br /> *<br /> * @Author: Aghatise Osazuwa<br /> * Website: www.cscprogrammingtutorials.com<br /> *<br /> * Exercise 3.12 - Modified Account Class<br /> * This Program Modifies Class Account (Fig. 3.13) In The Book To Provide<br /> * A Method Debit That Withdraws Money From An Account<br /> *<br /> */ <br /><br /> public class Ex03_12 {<br /><br /> private double balance;<br /><br /> public Ex03_12 (double initialBalance) {<br /> if (initialBalance > 0.0) <br /> balance = initialBalance;<br /> }<br /> <br /> public void credit (double amount) {<br /> balance = balance + amount;<br /> }<br /> <br /> public double getBalance () {<br /> return balance;<br /> }<br /> <br /> public void debit (double amount) {<br /> if (amount > balance)<br /> System.out.printf ("Debit amount exceeded account balance.n");<br /> if (amount == balance)<br /> balance = balance - amount;<br /> if (amount < balance)<br /> balance = balance - amount;<br /> }<br /><br />}<br /> |
Below is Class Ex03_12_Test.java to test Class Ex03_12.java
1 2 |
//Exercise 3.12 - Modified Account Class Test<br />//This Program Tests Method Debit Of Ex03_12<br /><br />import java.util.Scanner;<br /><br />public class Ex03_12_Test {<br /> public static void main (String [] args) {<br /><br /> Ex03_12 account = new Ex03_12 (0.0);<br /><br /> Scanner input = new Scanner (System.in);<br /> <br /> System.out.printf ("Your Account Balance is: $%.2fnn", account.getBalance());<br /> <br /> System.out.printf ("Enter Deposit Amount: ");<br /> double depositAmount = input.nextDouble();<br /> <br /> System.out.printf ("nAdding %.2f to your account balancenn", depositAmount);<br /> account.credit(depositAmount);<br /> <br /> System.out.printf ("Your Account Balance is: $%.2fnn", account.getBalance());<br /> <br /> System.out.printf ("Enter Debit Amount: ");<br /> double debitAmount = input.nextDouble();<br /> <br /> System.out.printf ("nDebiting %.2f from your account balancenn", debitAmount);<br /> account.debit(debitAmount);<br /> <br /> System.out.printf ("Your Account Balance is: $%.2fnn", account.getBalance());<br /><br /> }<br />}<br /> |