my cool blog

whats up

Unit 5 Lesson HACKS • 25 min read

Hacks

5.1-5.3 Hacks

POPCORN HACKS: 0.2

Create a simple To-Do List that utilizes the following (0.8):

  1. Private and Public Declaration

  2. Constructor

  3. Mutable Array containing To-Do List Items

Make sure to add descriptive comments that are describing your code!

TO DO LIST HACKS

import java.util.Scanner;

public class ToDoList {
    private String[] todos;    // Private array to store To-Do items.
    private int index;         // Private index to keep track of the number of items.
    private Scanner scanner;  // Private scanner for user input.

    public ToDoList() {       // Constructor to initialize the ToDoList object.
        todos = new String[10];  // Initialize the todos array with a size of 10.
        index = 0;              // Initialize the index to 0.
        scanner = new Scanner(System.in);  // Initialize the scanner for user input.
    }

    public void addTodo() {    // Public method to add a To-Do item.
        if (index < todos.length) {
            System.out.println("Enter a todo:");
            String userInput = scanner.nextLine();
            todos[index] = userInput;  // Store the user's input in the todos array.
            index++;  // Increment the index to keep track of the number of items.
        } else {
            System.out.println("To-Do list is full. Cannot add more items.");
        }
    }

    public void displayTodos() {  // Public method to display the To-Do items.
        System.out.println("To-Do List:");
        for (int i = 0; i < index; i++) {
            System.out.println(i + 1 + ". " + todos[i]);  // Display each To-Do item.
        }
    }

    public static void main(String[] args) {
        ToDoList toDoList = new ToDoList();  // Create an instance of the ToDoList class.
        Scanner scanner = new Scanner(System.in);

        while (true) {
            System.out.println("Choose an option:");
            System.out.println("1. Add Todo");
            System.out.println("2. Display Todos");
            System.out.println("3. Quit");
            int choice = scanner.nextInt();

            switch (choice) {
                case 1:
                    toDoList.addTodo();  // Call the addTodo method to add a To-Do item.
                    break;
                case 2:
                    toDoList.displayTodos();  // Call the displayTodos method to display To-Do items.
                    break;
                case 3:
                    System.out.println("Exiting the ToDo List application.");
                    scanner.close();  // Close the scanner when the program exits.
                    return;
                default:
                    System.out.println("Invalid choice. Please try again.");
                    break;
            }
        }
    }
}

ToDoList.main(null);  // Start the ToDoList application by calling the main method.


ToDoList.main(null);
Choose an option:
1. Add Todo
2. Display Todos
3. Quit


Enter a todo:
Choose an option:
1. Add Todo
2. Display Todos
3. Quit
Enter a todo:
Choose an option:
1. Add Todo
2. Display Todos
3. Quit
To-Do List:
1. buy toaster
2. repair toaster
Choose an option:
1. Add Todo
2. Display Todos
3. Quit
To-Do List:
1. buy toaster
2. repair toaster
Choose an option:
1. Add Todo
2. Display Todos
3. Quit
Exiting the ToDo List application.
Choose an option:
1. Add Todo
2. Display Todos
3. Quit
Exiting the ToDo List application.

5.9-5.10 Hacks

POPCORN HACKS: 0.2

Write a two sentence reflection on the social and ethical implications of programming. (0.8)

reflection

Programming is pretty damn powerful, and people have made lots of good and bad programs. Its pretty important that programming remains ethical and safe, to ensure that people don’t get scammed or the tech-illiterate are not taken advantage of when they dive into the world of tech and programming.

5.4-5.8 Hacks

POPCORN HACKS: 0.2 Make simple banking application. The application should be able to handle new customer bank account requests, processing deposits and withdrawals, and maintaining accurate records of transactions and balances. The application should also track the bank’s total supply of money. Your code should utilize the following concepts(0.8): Scope and Access: Private and public modifiers used in classes. Method Decomposition: Each class has its own responsibility; methods are tasked with single operations. Non-Void Methods: Methods like getBalance(), getAccountNumber(), and getTotalBankDeposits(). Void Methods: Methods like deposit(), withdraw(), and processTransaction(). Formal Parameters: Used in methods throughout the classes. Reference vs. Primitive Parameters: Primitive types for account numbers, balances, etc., and references for account objects.

NOTE

these hacks were really confusing for me, and I did use chat to help me out. I don’t really understand calling classes from classes, so I just have it in a single class.

MULTIPLE CLASS VERSION. DOES NOT RUN BUT RUNS IN JAVA KERNEL ONLINE

import java.util.ArrayList;
import java.util.List;

// Scope and Access: Private and public modifiers used in classes.

class Bank {
    private List<Account> accounts; // Private field to store a list of accounts.
    private double totalBankDeposits; // Private field to store the total bank deposits.

    public Bank() {
        accounts = new ArrayList<>(); // Public constructor to initialize the list of accounts.
        totalBankDeposits = 0.0; // Public constructor to initialize the total bank deposits.
    }

    public Account openAccount(String customerName, double initialBalance) {
        // Public method to open a new account.
        Account newAccount = new Account(customerName, initialBalance);
        accounts.add(newAccount);
        totalBankDeposits += initialBalance;
        return newAccount;
    }

    public double getTotalBankDeposits() {
        // Public method to get the total bank deposits.
        return totalBankDeposits;
    }

    public Account findAccount(int accountNumber) {
        // Public method to find an account by its account number.
        for (Account account : accounts) {
            if (account.getAccountNumber() == accountNumber) {
                return account;
            }
        }
        return null;
    }
}

class Account {
    // Scope and Access: Private and public modifiers used in classes.
    private static int nextAccountNumber = 1000; // Private static field for the next account number.
    private int accountNumber; // Private field to store the account number.
    private String customerName; // Private field to store the customer name.
    private double balance; // Private field to store the account balance.

    public Account(String customerName, double initialBalance) {
        // Public constructor to create a new account.
        this.accountNumber = nextAccountNumber++;
        this.customerName = customerName;
        this.balance = initialBalance;
    }

    // Non-Void Methods: Methods like getBalance(), getAccountNumber(), and getTotalBankDeposits().
    public int getAccountNumber() {
        // Public method to get the account number.
        return accountNumber;
    }

    public String getCustomerName() {
        // Public method to get the customer name.
        return customerName;
    }

    public double getBalance() {
        // Public method to get the account balance.
        return balance;
    }

    // Void Methods: Methods like deposit(), withdraw(), and processTransaction().
    public void deposit(double amount) {
        // Public method to deposit funds into the account.
        balance += amount;
    }

    public boolean withdraw(double amount) {
        // Public method to withdraw funds from the account.
        if (amount <= balance) {
            balance -= amount;
            return true;
        } else {
            return false; // Insufficient balance
        }
    }

    public void processTransaction(Transaction transaction) {
        // Public method to process a transaction.
        if (transaction.getType() == TransactionType.DEPOSIT) {
            deposit(transaction.getAmount());
        } else if (transaction.getType() == TransactionType.WITHDRAW) {
            boolean success = withdraw(transaction.getAmount());
            if (success) {
                transaction.setStatus(TransactionStatus.COMPLETED);
            } else {
                transaction.setStatus(TransactionStatus.FAILED);
            }
        }
    }
}

enum TransactionType {
    DEPOSIT, WITHDRAW
}

enum TransactionStatus {
    PENDING, COMPLETED, FAILED
}

class Transaction {
    private TransactionType type;
    private double amount;
    private TransactionStatus status;

    public Transaction(TransactionType type, double amount) {
        this.type = type;
        this.amount = amount;
        this.status = TransactionStatus.PENDING;
    }

    public TransactionType getType() {
        return type;
    }

    public double getAmount() {
        return amount;
    }

    public TransactionStatus getStatus() {
        return status;
    }

    public void setStatus(TransactionStatus status) {
        this.status = status;
    }
}

public class BankingApplication {
    public static void main(String[] args) {
        Bank bank = new Bank();
        Account account1 = bank.openAccount("John Doe", 1000.0);

        Transaction depositTransaction = new Transaction(TransactionType.DEPOSIT, 500.0);
        account1.processTransaction(depositTransaction);

        Transaction withdrawTransaction = new Transaction(TransactionType.WITHDRAW, 300.0);
        account1.processTransaction(withdrawTransaction);

        System.out.println("Account Number: " + account1.getAccountNumber());
        System.out.println("Customer Name: " + account1.getCustomerName());
        System.out.println("Current Balance: $" + account1.getBalance());
        System.out.println("Total Bank Deposits: $" + bank.getTotalBankDeposits());
    }
}

SIMPLIFIED BANKING VERSION. DOES NOT HAVE MULTIPLE CLASSES BUT RUNS.

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class SimpleBankingProgram {
    public static void main(String[] args) {
        Map<String, Double> accounts = new HashMap<>();
        accounts.put("user123", 1000.0);
        Scanner scanner = new Scanner(System.in);

        boolean exit = false;
        while (!exit) {
            System.out.println("\nSimple Banking Program");
            System.out.println("1. Check Balance");
            System.out.println("2. Deposit");
            System.out.println("3. Withdraw");
            System.out.println("4. Exit");
            System.out.print("Select an option (1/2/3/4): ");

            int choice = scanner.nextInt();

            switch (choice) {
                case 1:
                    System.out.print("Enter your username: ");
                    String username = scanner.next();
                    double balance = accounts.getOrDefault(username, 0.0);
                    System.out.println("Your balance is: " + balance);
                    break;
                case 2:
                    System.out.print("Enter your username: ");
                    String depositUsername = scanner.next();
                    System.out.print("Enter the amount to deposit: ");
                    double depositAmount = scanner.nextDouble();
                    double currentBalance = accounts.getOrDefault(depositUsername, 0.0);
                    accounts.put(depositUsername, currentBalance + depositAmount);
                    System.out.println("Deposit successful. Your new balance is: " + accounts.get(depositUsername));
                    break;
                case 3:
                    System.out.print("Enter your username: ");
                    String withdrawUsername = scanner.next();
                    System.out.print("Enter the amount to withdraw: ");
                    double withdrawAmount = scanner.nextDouble();
                    currentBalance = accounts.getOrDefault(withdrawUsername, 0.0);
                    if (currentBalance >= withdrawAmount) {
                        accounts.put(withdrawUsername, currentBalance - withdrawAmount);
                        System.out.println("Withdrawal successful. Your new balance is: " + accounts.get(withdrawUsername));
                    } else {
                        System.out.println("Insufficient balance for withdrawal.");
                    }
                    break;
                case 4:
                    exit = true;
                    System.out.println("Thank you for using Simple Banking Program!");
                    break;
                default:
                    System.out.println("Invalid option. Select a valid option (1/2/3/4).");
            }
        }
        scanner.close();
    }
}


SimpleBankingProgram.main(null);
Simple Banking Program
1. Check Balance
2. Deposit
3. Withdraw
4. Exit
Select an option (1/2/3/4): 

Enter your username: Your balance is: 1000.0

Simple Banking Program
1. Check Balance
2. Deposit
3. Withdraw
4. Exit
Select an option (1/2/3/4): Enter your username: Enter the amount to deposit: Deposit successful. Your new balance is: 1690.0

Simple Banking Program
1. Check Balance
2. Deposit
3. Withdraw
4. Exit
Select an option (1/2/3/4): Enter your username: Your balance is: 1690.0

Simple Banking Program
1. Check Balance
2. Deposit
3. Withdraw
4. Exit
Select an option (1/2/3/4): Enter your username: Enter the amount to withdraw: Withdrawal successful. Your new balance is: 688.0

Simple Banking Program
1. Check Balance
2. Deposit
3. Withdraw
4. Exit
Select an option (1/2/3/4): Enter your username: Your balance is: 688.0

Simple Banking Program
1. Check Balance
2. Deposit
3. Withdraw
4. Exit
Select an option (1/2/3/4): Thank you for using Simple Banking Program!
Scroll to top