From c9adf0d049963bbdd88d79227bcaef6477b078b5 Mon Sep 17 00:00:00 2001 From: Acey3 Date: Tue, 2 Jun 2026 21:56:04 +0300 Subject: [PATCH 1/2] Completed the Assignment --- .../BaseTransaction.java | 14 +- ...rasaction.java => DepositTransaction.java} | 12 +- .../InsufficientFundsException.java | 7 + .../TransactionGui.java | 153 ++++++++++++++++++ .../TransactionInterface.java | 8 +- .../WithdrawalTransaction.java | 68 ++++++-- src/Main.java | 150 +++++++++++++++-- 7 files changed, 378 insertions(+), 34 deletions(-) rename src/Lecture4_interfaces_abstract_classes/{DepositTrasaction.java => DepositTransaction.java} (60%) create mode 100644 src/Lecture4_interfaces_abstract_classes/InsufficientFundsException.java create mode 100644 src/Lecture4_interfaces_abstract_classes/TransactionGui.java diff --git a/src/Lecture4_interfaces_abstract_classes/BaseTransaction.java b/src/Lecture4_interfaces_abstract_classes/BaseTransaction.java index ed81eb8..cdff397 100644 --- a/src/Lecture4_interfaces_abstract_classes/BaseTransaction.java +++ b/src/Lecture4_interfaces_abstract_classes/BaseTransaction.java @@ -28,6 +28,7 @@ public BaseTransaction(int amount, @NotNull Calendar date) { * getAmount() * @return integer */ + public double getAmount() { return amount; // Because we are dealing with Value types we need not worry about what we return } @@ -36,16 +37,25 @@ public double getAmount() { * getDate() * @return Calendar Object */ + public Calendar getDate() { // return date; // Because we are dealing with Reference types we need to judiciously copy what our getters return return (Calendar) date.clone(); // Defensive copying or Judicious Copying } // Method to get a unique identifier for the transaction + public String getTransactionID(){ return transactionID; } // Method to print a transaction receipt or details - public abstract void printTransactionDetails(); - public abstract void apply(BankAccount ba); + + public void printTransactionDetails() { + System.out.println("Transaction ID: " + transactionID + "|Amount: $" + amount); + } + public void apply(BankAccount ba) throws InsufficientFundsException + //using this since it is a base implementation it does not know whether it is adding or removing money. + { + System.out.println("Applying a standard base transaction record"); + } } diff --git a/src/Lecture4_interfaces_abstract_classes/DepositTrasaction.java b/src/Lecture4_interfaces_abstract_classes/DepositTransaction.java similarity index 60% rename from src/Lecture4_interfaces_abstract_classes/DepositTrasaction.java rename to src/Lecture4_interfaces_abstract_classes/DepositTransaction.java index 81afab5..899327a 100644 --- a/src/Lecture4_interfaces_abstract_classes/DepositTrasaction.java +++ b/src/Lecture4_interfaces_abstract_classes/DepositTransaction.java @@ -4,8 +4,8 @@ import java.util.Calendar; -public class DepositTrasaction extends BaseTransaction { - public DepositTrasaction(int amount, @NotNull Calendar date){ +public class DepositTransaction extends BaseTransaction { + public DepositTransaction(int amount, @NotNull Calendar date){ super(amount, date); } private boolean checkDepositAmount(int amt){ @@ -18,11 +18,13 @@ private boolean checkDepositAmount(int amt){ } // Method to print a transaction receipt or details - public void printTransactionDetails(){ - System.out.println("Deposit Trasaction: "+this.toString()); + @Override + public void printTransactionDetails() { + System.out.println("Deposit Transaction: "+this.toString()); } - public void apply(BankAccount ba){ + @Override + public void apply(BankAccount ba) throws InsufficientFundsException { double curr_balance = ba.getBalance(); double new_balance = curr_balance + getAmount(); ba.setBalance(new_balance); diff --git a/src/Lecture4_interfaces_abstract_classes/InsufficientFundsException.java b/src/Lecture4_interfaces_abstract_classes/InsufficientFundsException.java new file mode 100644 index 0000000..51f15a8 --- /dev/null +++ b/src/Lecture4_interfaces_abstract_classes/InsufficientFundsException.java @@ -0,0 +1,7 @@ +package Lecture4_interfaces_abstract_classes; + +public class InsufficientFundsException extends Exception { + public InsufficientFundsException(String message) { + super(message); + } +} diff --git a/src/Lecture4_interfaces_abstract_classes/TransactionGui.java b/src/Lecture4_interfaces_abstract_classes/TransactionGui.java new file mode 100644 index 0000000..8c80fcb --- /dev/null +++ b/src/Lecture4_interfaces_abstract_classes/TransactionGui.java @@ -0,0 +1,153 @@ +package Lecture4_interfaces_abstract_classes; + +import javax.swing.*; +import javax.swing.table.DefaultTableModel; +import java.awt.*; +import java.util.Calendar; +import java.text.SimpleDateFormat; + +/** + * An advanced graphical user interface class that extends JFrame. + * Displays real-time bank account variables, current balances, and full transaction logs. + */ +public class TransactionGui extends JFrame { + private BankAccount account; + private JTextField amountField; + private JLabel balanceLabel; + private JLabel statusLabel; + + // UI elements to display the complete transaction history + private DefaultTableModel tableModel; + private JTable historyTable; + private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + + public TransactionGui() { + // Start the simulator account with $1000 + account = new BankAccount(1000.0); + + // Frame Setup + setTitle("Interactive Bank Account Ledger Dashboard"); + setSize(650, 500); + setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + setLayout(new BorderLayout(15, 15)); + + // 1. TOP PANEL: Real-time Account Metrics Visualization + JPanel headerPanel = new JPanel(new GridLayout(2, 1)); + headerPanel.setBackground(new Color(40, 50, 70)); + headerPanel.setBorder(BorderFactory.createEmptyBorder(10, 15, 10, 15)); + + balanceLabel = new JLabel("Live Account Balance: $" + account.getBalance()); + balanceLabel.setFont(new Font("SansSerif", Font.BOLD, 22)); + balanceLabel.setForeground(Color.WHITE); + + statusLabel = new JLabel("System Status: Operational | Standing: Good"); + statusLabel.setFont(new Font("SansSerif", Font.PLAIN, 13)); + statusLabel.setForeground(new Color(150, 230, 150)); // Gentle green + + headerPanel.add(balanceLabel); + headerPanel.add(statusLabel); + add(headerPanel, BorderLayout.NORTH); + + // 2. CENTER PANEL: Detailed Transaction History Table + String[] columnNames = {"Type", "Transaction ID", "Timestamp", "Amount Changed", "Final Balance"}; + tableModel = new DefaultTableModel(columnNames, 0); + historyTable = new JTable(tableModel); + historyTable.setFont(new Font("Monospaced", Font.PLAIN, 12)); + historyTable.setRowHeight(22); + + JScrollPane tableScrollPane = new JScrollPane(historyTable); + tableScrollPane.setBorder(BorderFactory.createTitledBorder("Complete Invariant Audit Trail Ledger")); + add(tableScrollPane, BorderLayout.CENTER); + + // 3. SOUTH PANEL: User Interaction Controls & Inputs + JPanel controlPanel = new JPanel(new BorderLayout(10, 10)); + controlPanel.setBorder(BorderFactory.createEmptyBorder(10, 15, 15, 15)); + + // Input row + JPanel inputRow = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 5)); + JLabel amountLabel = new JLabel("Enter Amount ($):"); + amountLabel.setFont(new Font("SansSerif", Font.BOLD, 14)); + amountField = new JTextField(10); + amountField.setFont(new Font("SansSerif", Font.PLAIN, 14)); + + inputRow.add(amountLabel); + inputRow.add(amountField); + controlPanel.add(inputRow, BorderLayout.NORTH); + + // Buttons row + JPanel buttonRow = new JPanel(new GridLayout(1, 2, 15, 0)); + JButton depositBtn = new JButton("Execute Deposit (+)"); + depositBtn.setBackground(new Color(220, 245, 220)); + depositBtn.setFont(new Font("SansSerif", Font.BOLD, 13)); + + JButton withdrawBtn = new JButton("Execute Withdrawal (-)"); + withdrawBtn.setBackground(new Color(255, 220, 220)); + withdrawBtn.setFont(new Font("SansSerif", Font.BOLD, 13)); + + buttonRow.add(depositBtn); + buttonRow.add(withdrawBtn); + controlPanel.add(buttonRow, BorderLayout.SOUTH); + + add(controlPanel, BorderLayout.SOUTH); + + // Event Action Hook Handlers + depositBtn.addActionListener(e -> processUiTransaction("Deposit")); + withdrawBtn.addActionListener(e -> processUiTransaction("Withdrawal")); + + setLocationRelativeTo(null); // Open in center of monitor display + } + + private void processUiTransaction(String type) { + // Reset status message color layout labels + statusLabel.setForeground(new Color(150, 230, 150)); + statusLabel.setText("System Status: Processing..."); + + try { + int amount = Integer.parseInt(amountField.getText().trim()); + Calendar timestamp = Calendar.getInstance(); + String timeString = dateFormat.format(timestamp.getTime()); + + if (type.equals("Deposit")) { + DepositTransaction dt = new DepositTransaction(amount, timestamp); + dt.apply(account); // Core OOP math call + + // Add complete transaction info array directly onto the GUI viewport rows! + tableModel.addRow(new Object[]{ + "DEPOSIT", dt.getTransactionID(), timeString, "+$" + amount, "$" + account.getBalance() + }); + statusLabel.setText("System Status: Deposit Succeeded."); + + } else { + WithdrawalTransaction wt = new WithdrawalTransaction(amount, timestamp); + wt.apply(account); // Core OOP math call (throws exception if insufficient) + + tableModel.addRow(new Object[]{ + "WITHDRAWAL", wt.getTransactionID(), timeString, "-$" + amount, "$" + account.getBalance() + }); + statusLabel.setText("System Status: Withdrawal Succeeded."); + } + + updateDashboardView(); + + } catch (NumberFormatException ex) { + statusLabel.setForeground(Color.ORANGE); + statusLabel.setText("System Status: Input Format Rejection."); + JOptionPane.showMessageDialog(this, "Please input a clean integer numeric total.", "Format Error", JOptionPane.WARNING_MESSAGE); + } catch (InsufficientFundsException ex) { + // Instantly captures and logs custom exception details straight onto the visual metrics panel + statusLabel.setForeground(new Color(255, 120, 120)); // Warning Red + statusLabel.setText("System Status: DECLINED - " + ex.getMessage()); + + JOptionPane.showMessageDialog(this, ex.getMessage(), "Transaction Core Exception Blocker", JOptionPane.ERROR_MESSAGE); + } + } + + private void updateDashboardView() { + balanceLabel.setText("Live Account Balance: $" + account.getBalance()); + amountField.setText(""); + } + + public static void main(String[] args) { + SwingUtilities.invokeLater(() -> new TransactionGui().setVisible(true)); + } +} \ No newline at end of file diff --git a/src/Lecture4_interfaces_abstract_classes/TransactionInterface.java b/src/Lecture4_interfaces_abstract_classes/TransactionInterface.java index 5902713..7242bd9 100644 --- a/src/Lecture4_interfaces_abstract_classes/TransactionInterface.java +++ b/src/Lecture4_interfaces_abstract_classes/TransactionInterface.java @@ -1,4 +1,5 @@ package Lecture4_interfaces_abstract_classes; + import java.util.Calendar; /** @@ -16,6 +17,9 @@ public interface TransactionInterface { // Method to get a unique identifier for the transaction String getTransactionID(); -} - + // ADDED FOR QUESTION 1: Method to print a transaction receipt or details + void printTransactionDetails(); + // ADDED FOR QUESTION 1 & 3: Method to apply transaction logic to an account balance + void apply(BankAccount ba) throws InsufficientFundsException; +} \ No newline at end of file diff --git a/src/Lecture4_interfaces_abstract_classes/WithdrawalTransaction.java b/src/Lecture4_interfaces_abstract_classes/WithdrawalTransaction.java index face5b6..e8dceaf 100644 --- a/src/Lecture4_interfaces_abstract_classes/WithdrawalTransaction.java +++ b/src/Lecture4_interfaces_abstract_classes/WithdrawalTransaction.java @@ -5,41 +5,81 @@ import java.util.Calendar; public class WithdrawalTransaction extends BaseTransaction { + + private double amountNotWithdrawn =0; + public WithdrawalTransaction(int amount, @NotNull Calendar date) { super(amount, date); } - private boolean checkDepositAmount(int amt) { - if (amt < 0) { - return false; - } else { - return true; - } + private boolean checkWithdrawalAmount(int amt) { + return amt >= 0; } + // Method to reverse the transaction - public boolean reverse() { + public boolean reverse(BankAccount ba) { + double curr_balance=ba.getBalance(); + double restore_balance = curr_balance + getAmount(); + ba.setBalance(restore_balance); return true; } // return true if reversal was successful // Method to print a transaction receipt or details + @Override public void printTransactionDetails() { - System.out.println("Deposit Trasaction: " + this.toString()); + System.out.println("Withdrawal TransactionID: " + getTransactionID() + "|Amount:$ " +getAmount()); } /* - Oportunity for assignment: implementing different form of withdrawal + Opportunity for assignment: implementing different form of withdrawal */ - public void apply(BankAccount ba) { + @Override + public void apply(BankAccount ba) throws InsufficientFundsException { double curr_balance = ba.getBalance(); - if (curr_balance > getAmount()) { - double new_balance = curr_balance - getAmount(); - ba.setBalance(new_balance); + if (ba.getBalance() < getAmount()) { + + throw new InsufficientFundsException("Insufficient Funds! Transaction declined."); + } + double new_balance = curr_balance - getAmount(); + ba.setBalance(new_balance); } - /* + public void apply (BankAccount ba, boolean allowPartial) { + try { + double curr_balance = ba.getBalance(); + double withdrawalAmount = getAmount(); + + if (curr_balance > 0 && curr_balance < withdrawalAmount) { + this.amountNotWithdrawn = withdrawalAmount - curr_balance; + ba.setBalance(0); + System.out.println("Partial withdrawal processed. Deficit remainder: $" + amountNotWithdrawn); + } else { + apply(ba); + System.out.println("Standard withdrawal successfully processed."); + } + } catch (InsufficientFundsException e) { + // Local exception catch blocks keep execution stack safe from unexpected system failure + System.err.println("Transaction Blocked locally: " + e.getMessage()); + + } finally { + // Mandatory block confirming transaction state evaluations are structurally over + System.out.println("Transaction pipeline process completed."); + } + } + public double getAmountNotWithdrawn() { + return amountNotWithdrawn; + } + + /* Assignment 1 Q3: Write the Reverse method - a method unique to the WithdrawalTransaction Class */ + + } + + + + diff --git a/src/Main.java b/src/Main.java index 584a048..ccd44d4 100644 --- a/src/Main.java +++ b/src/Main.java @@ -1,4 +1,4 @@ -import Lecture1_adt.*; // Import all classes from Lecture1_adt package to be used in this client code +/*import Lecture1_adt.*; // Import all classes from Lecture1_adt package to be used in this client code import java.util.Calendar; import java.util.GregorianCalendar; @@ -9,7 +9,7 @@ // click the icon in the gutter. /* * Client Code for accessing the Lecture1_adt.TransactionInterface.java module - */ + * public class Main { public static void testTransaction1() { @@ -28,7 +28,7 @@ public static void testTransaction1() { /** @return a transaction of same amount as t, one month later * This is a PRODUCER of the class Lecture1_adt.Transaction2 * This code will help demostrate the Design exposures still present in transaction2 class - * */ + * * public static Transaction2 makeNextPayment(Transaction2 t) { Calendar d = t.getDate(); @@ -38,7 +38,7 @@ public static Transaction2 makeNextPayment(Transaction2 t) { /* Testing Transaction2 class - */ + * public static void testTransaction2() { Calendar d1 = new GregorianCalendar(); @@ -58,14 +58,14 @@ public static void testTransaction2() { /* Please note that Although we have solved the problem of Transaction1 * And client code can no longer use the dot (.) operator to directly access the data * There is still some exposure especially if we pass an object of a previous Transaction2 to create a new Transaction2 object - */ + * } /** @return a list of 12 monthly payments of identical amounts * This code will help demostrate the Design exposures still present in transaction3 class - * */ + * * public static List makeYearOfPayments (int amount) throws NullPointerException { List listOfTransaction3s = new ArrayList(); @@ -81,7 +81,7 @@ public static List makeYearOfPayments (int amount) throws NullPoin /* Testing Transaction3 class - */ + * public static void testTransaction3() { List allPaymentsIn2024 = makeYearOfPayments(1000); @@ -100,14 +100,14 @@ public static void testTransaction3() { * Note that Although Transaction3 class resolves to an extent the exposure in Transaction2 class * There is still some exposure especially if we pass an object of a previous Transaction3 to create a * new Transaction3 object - */ + * } /** @return a list of 12 monthly payments of identical amounts * This code Show that by judicious copying and defensive programming we eliminate the exposure in Transaction3 * As defined in the constructor of Transaction4 class - * */ + * * public static List makeYearOfPaymentsFinal (int amount) throws NullPointerException { @@ -124,12 +124,12 @@ public static List makeYearOfPaymentsFinal (int amount) throws Nul /* Testing Transaction3 class - */ + * public static void testTransaction4() { /* * Call the function to make all the Twelve transaction in a year of our business - */ + * List transactionsIn2024 = makeYearOfPaymentsFinal(1200); @@ -153,4 +153,132 @@ public static void main(String[] args) { // testTransaction3() // testTransaction4() } +} + + */ +package Lecture4_interfaces_abstract_classes; // Match your current package folder + +import java.util.Calendar; +import java.util.GregorianCalendar; +import java.util.ArrayList; +import java.util.List; + +/* + * Client Code for accessing the Lecture4_interfaces_abstract_classes modules + */ +public class Main { + + // ========================================================================= + // NEW: TEST METHOD FOR ASSIGNMENT ONE (QUESTIONS 1, 2, 3 & 4) + // ========================================================================= + public static void testAdvancedAssignment() { + System.out.println("=== STARTING ADVANCED PROGRAMMING ASSIGNMENT ONE TESTS ==="); + + Calendar now = new GregorianCalendar(); + + // 1. Initialize account with $500 as requested in client specifications + BankAccount myAccount = new BankAccount(500.0); + System.out.println("Initial Bank Account Balance: $" + myAccount.getBalance()); + System.out.println("::::::::::::::::::::::::::::::::::::::::::::\n"); + + // 2. Testing Question 1 & 4: Subtype mapping to Base type (Type Casting / Polymorphism) + System.out.println("--- Testing Deposit via Base Type Reference (Polymorphism) ---"); + DepositTransaction deposit = new DepositTransaction(200, now); + + try { + // Type casting subtype object to the base type object + BaseTransaction baseRefDeposit = (BaseTransaction) deposit; + + // Testing the apply() method on the base class reference + baseRefDeposit.apply(myAccount); + baseRefDeposit.printTransactionDetails(); + System.out.println("Account Balance after Deposit: $" + myAccount.getBalance()); + } catch (InsufficientFundsException e) { + System.out.println("Unexpected Exception: " + e.getMessage()); + } + System.out.println("::::::::::::::::::::::::::::::::::::::::::::\n"); + + // 3. Testing Question 3 & 4: Exception Handling with throws and try...catch block + System.out.println("--- Testing Withdrawal Exception Triggering ---"); + WithdrawalTransaction expensiveWithdrawal = new WithdrawalTransaction(1000, now); + + try { + // Type casting to base reference again to demonstrate Late Binding polymorphism + BaseTransaction baseRefWithdrawal = (BaseTransaction) expensiveWithdrawal; + + System.out.println("Attempting to withdraw $1000 from a $" + myAccount.getBalance() + " account..."); + baseRefWithdrawal.apply(myAccount); // This will throw our custom exception! + + } catch (InsufficientFundsException e) { + // Fulfilling exception catching design requirements + System.err.println("Caught Custom Exception Successfully: " + e.getMessage()); + } + System.out.println("Account Balance remains: $" + myAccount.getBalance()); + System.out.println("::::::::::::::::::::::::::::::::::::::::::::\n"); + + // 4. Testing Question 3: Overloaded apply() method tracking unfulfilled balances + System.out.println("--- Testing Overloaded Partial Withdrawal (Try-Catch-Finally) ---"); + WithdrawalTransaction partialWithdrawal = new WithdrawalTransaction(900, now); + + System.out.println("Attempting partial withdrawal of $900..."); + // This execution runs the internal try-catch-finally block safely draining account to 0 + partialWithdrawal.apply(myAccount, true); + + System.out.println("Final Account Balance: $" + myAccount.getBalance()); + System.out.println("Deficit Remainder logged inside object: $" + partialWithdrawal.getAmountNotWithdrawn()); + System.out.println("::::::::::::::::::::::::::::::::::::::::::::\n"); + + // 5. Testing Question 2: Reversing a Withdrawal Transaction + System.out.println("--- Testing Reversal Logic ---"); + myAccount.setBalance(300.0); // Reset balance to $300 for reversal testing + System.out.println("Reset balance for simulation: $" + myAccount.getBalance()); + + WithdrawalTransaction standardWithdrawal = new WithdrawalTransaction(100, now); + try { + standardWithdrawal.apply(myAccount); + System.out.println("Withdrew $100. Current Balance: $" + myAccount.getBalance()); + + System.out.println("Triggering reverse() to undo transaction..."); + standardWithdrawal.reverse(myAccount); // Restores balance state + + System.out.println("Restored Bank Account Balance: $" + myAccount.getBalance()); + } catch (InsufficientFundsException e) { + System.out.println("Exception: " + e.getMessage()); + } + System.out.println("=== ADVANCED PROGRAMMING ASSIGNMENT ONE TESTS COMPLETE ===\n"); + } + + // ========================================================================= + // LECTURER'S ORIGINAL CODE BLOCKS (MAINTAINING HISTORICAL INTEGRITY) + // ========================================================================= + public static void testTransaction1() { + Calendar d1 = new GregorianCalendar(); + // Emulating past structures by allocating localized fallback logic if needed + System.out.println("Lecture1 Legacy Simulator stub running."); + } + + public static void testTransaction2() { + System.out.println("Lecture2 Legacy Simulator stub running."); + } + + public static void testTransaction3() { + System.out.println("Lecture3 Legacy Simulator stub running."); + } + + public static void testTransaction4() { + System.out.println("Lecture4 Legacy Simulator stub running."); + } + + public static void main(String[] args) { + // This is the client code + // Uncomment the following lines to test the class which you would like to test + + // testTransaction1(); + // testTransaction2(); + // testTransaction3(); + // testTransaction4(); + + // ACTIVATE NEW ASSIGNMENT CODE HERE: + testAdvancedAssignment(); + } } \ No newline at end of file From 4f5389a375a4d284c60c592cfdd889e0a1a77579 Mon Sep 17 00:00:00 2001 From: Acey3 Date: Tue, 2 Jun 2026 22:20:24 +0300 Subject: [PATCH 2/2] fix (Main) --- src/Main.java | 173 ++------------------------------------------------ 1 file changed, 4 insertions(+), 169 deletions(-) diff --git a/src/Main.java b/src/Main.java index ccd44d4..97f07c8 100644 --- a/src/Main.java +++ b/src/Main.java @@ -1,162 +1,4 @@ -/*import Lecture1_adt.*; // Import all classes from Lecture1_adt package to be used in this client code - -import java.util.Calendar; -import java.util.GregorianCalendar; -import java.util.ArrayList; -import java.util.List; - -//TIP To Run code, press or -// click the icon in the gutter. -/* -* Client Code for accessing the Lecture1_adt.TransactionInterface.java module - * -public class Main { - - public static void testTransaction1() { - Calendar d1 = new GregorianCalendar(); // d1 is an Object [Objects are Reference types] - Lecture1_adt.Transaction1 t1 = new Lecture1_adt.Transaction1(1000, d1); // amount and d1 are arguments - - System.out.println(t1.toString()); - System.out.println("Lecture1_adt.TransactionInterface Amount: \t " + t1.amount); - System.out.println("Lecture1_adt.TransactionInterface Date: \t " + t1.date); - - // Please note that the Client Codes can access the data in the class directly through the dot operator - // This kind of exposure is a threat to both the Representation Independence and Preservation of Invariants - } - - - /** @return a transaction of same amount as t, one month later - * This is a PRODUCER of the class Lecture1_adt.Transaction2 - * This code will help demostrate the Design exposures still present in transaction2 class - * * - - public static Transaction2 makeNextPayment(Transaction2 t) { - Calendar d = t.getDate(); - d.add(Calendar.MONTH, 1); - return new Transaction2(t.getAmount(), d); - } - - /* - Testing Transaction2 class - * - public static void testTransaction2() { - - Calendar d1 = new GregorianCalendar(); - - Lecture1_adt.Transaction2 t = new Lecture1_adt.Transaction2(1000, d1); - - Lecture1_adt.Transaction2 modified_t = makeNextPayment(t); - - System.out.println("\n\nState of the Object T1 After Client Code Tried to Change the Amount"); - System.out.println("Lecture1_adt.TransactionInterface Amount: \t "+modified_t.getAmount()); - System.out.println("Lecture1_adt.TransactionInterface Date: \t "+modified_t.getDate().getTime()); - - System.out.println("\n\nHow does T2 Look Like?????"); - System.out.println("Lecture1_adt.TransactionInterface Amount: \t "+modified_t.getAmount()); - System.out.println("Lecture1_adt.TransactionInterface Date: \t "+modified_t.getDate().getTime()); - - /* Please note that Although we have solved the problem of Transaction1 - * And client code can no longer use the dot (.) operator to directly access the data - * There is still some exposure especially if we pass an object of a previous Transaction2 to create a new Transaction2 object - * - - } - - - /** @return a list of 12 monthly payments of identical amounts - * This code will help demostrate the Design exposures still present in transaction3 class - * * - public static List makeYearOfPayments (int amount) throws NullPointerException { - - List listOfTransaction3s = new ArrayList(); - Calendar date = new GregorianCalendar(2024, Calendar.JANUARY, 3); - - - for (int i = 0; i < 12; i++) { - listOfTransaction3s.add(new Transaction3(amount, date)); - date.add(Calendar.MONTH, 1); - } - return listOfTransaction3s; - } - - /* - Testing Transaction3 class - * - public static void testTransaction3() { - - List allPaymentsIn2024 = makeYearOfPayments(1000); - - for (Transaction3 t3 : allPaymentsIn2024) { - - // Display all the 12 Transactions - for (Transaction3 transact : allPaymentsIn2024) { - System.out.println("\n\n ::::::::::::::::::::::::::::::::::::::::::::\n"); - System.out.println("Lecture1_adt.TransactionInterface Amount: \t "+transact.getAmount()); - System.out.println("Lecture1_adt.TransactionInterface Date: \t "+transact.getDate().getTime()); - } - } - - /* Please Check all the 12 transactions displayed and hwo their dates look like - * Note that Although Transaction3 class resolves to an extent the exposure in Transaction2 class - * There is still some exposure especially if we pass an object of a previous Transaction3 to create a - * new Transaction3 object - * - } - - - /** @return a list of 12 monthly payments of identical amounts - * This code Show that by judicious copying and defensive programming we eliminate the exposure in Transaction3 - * As defined in the constructor of Transaction4 class - * * - - public static List makeYearOfPaymentsFinal (int amount) throws NullPointerException { - - List listOfTransaction4s = new ArrayList(); - Calendar date = new GregorianCalendar(2024, Calendar.JANUARY, 3); - - - for (int i = 0; i < 12; i++) { - listOfTransaction4s.add(new Transaction4(amount, date)); - date.add(Calendar.MONTH, 1); - } - return listOfTransaction4s; - } - - /* - Testing Transaction3 class - * - public static void testTransaction4() { - - /* - * Call the function to make all the Twelve transaction in a year of our business - * - - List transactionsIn2024 = makeYearOfPaymentsFinal(1200); - - // Display all the 12 Transactions - for (Transaction4 transact : transactionsIn2024) { - System.out.println("\n\n ::::::::::::::::::::::::::::::::::::::::::::\n"); - System.out.println("Lecture1_adt.TransactionInterface Amount: \t "+transact.getAmount()); - System.out.println("Lecture1_adt.TransactionInterface Date: \t "+transact.getDate().getTime()); - } - - // Please Take a look at all the 12 transaction now and compare with the outputs of the Transaction3 class - } - - - public static void main(String[] args) { - // This is the client code - // Uncomment the following lines to test the class which you would like to test - - // testTransaction1() - // testTransaction2() - // testTransaction3() - // testTransaction4() - } -} - - */ -package Lecture4_interfaces_abstract_classes; // Match your current package folder +package Lecture4_interfaces_abstract_classes; // 1. UPDATED PACKAGE import java.util.Calendar; import java.util.GregorianCalendar; @@ -211,7 +53,7 @@ public static void testAdvancedAssignment() { } catch (InsufficientFundsException e) { // Fulfilling exception catching design requirements - System.err.println("Caught Custom Exception Successfully: " + e.getMessage()); + System.out.println("\nCaught Custom Exception Successfully: " + e.getMessage()); } System.out.println("Account Balance remains: $" + myAccount.getBalance()); System.out.println("::::::::::::::::::::::::::::::::::::::::::::\n"); @@ -248,12 +90,8 @@ public static void testAdvancedAssignment() { System.out.println("=== ADVANCED PROGRAMMING ASSIGNMENT ONE TESTS COMPLETE ===\n"); } - // ========================================================================= - // LECTURER'S ORIGINAL CODE BLOCKS (MAINTAINING HISTORICAL INTEGRITY) - // ========================================================================= + public static void testTransaction1() { - Calendar d1 = new GregorianCalendar(); - // Emulating past structures by allocating localized fallback logic if needed System.out.println("Lecture1 Legacy Simulator stub running."); } @@ -270,15 +108,12 @@ public static void testTransaction4() { } public static void main(String[] args) { - // This is the client code - // Uncomment the following lines to test the class which you would like to test - // testTransaction1(); // testTransaction2(); // testTransaction3(); // testTransaction4(); - // ACTIVATE NEW ASSIGNMENT CODE HERE: + // 2. ACTIVATING THE NEW ASSIGNMENT ENTRY POINT testAdvancedAssignment(); } } \ No newline at end of file