I'm pretty new to OOP and Java and have a question that may be trivial but I couldn't find the answer on the web.
I'm doing the standard bank account program in Java- a program where there are customers, each customer has bank accounts (one customer may have more than one bank account!) and I can deposit or withdraw money. Each bank account has a unique number (even if someone has multiple bank account, each bank account has its unique number)
My code compiles and the operations deposit and withdraw are working correctly.
The problem is the following- I cannot attribute more than one bank account to a customer, in my program a client can have exactly one bank and no more than one bank account.
I have 3 classes - Account, Client, BankMain. You can see them below
public class Account {
private int balance;
private String NumAccount; // each bank account has a unique number
public Account(int money, String num) {
balance = money;
NumAccount = num;
}
public String printAccountNumber() {
return NumAccount;
}
// below are the methods for withdraw,deposit- they are working properly
}
Class Client
public class Client {
private String name;// name of the client
private Account account;
// the account associated to the client. Probably I should change sth
// here
// but I don't know what
public Client(String nom, Compte c) {
name = nom;
account = c;
}
public void printName() {
System.out.println(
"Name: " + name
+ "\nAccount number: " + account.printAccountNumber()
+ "\nSolde: " + account.printBalance() + "\n"
);
}
}
And BankMain
public class BankMain {
public static void main(String[] args) {
Account account1 = new Account(1000, "11223A");
Account account2 = new Account(10000, "11111A");
Client client1 = new Client("George", account1);
Client client2 = new Client("Oliver", account2);
// now this is working correctly
client1.printName();
client2.ptintName();
/*
* The problem is that I don't know what to do if I want account1
* and account2 to belong both to client1. I tried Client client1 =
* new Client("George",account1); Client client1 = new
* Client("Oliver", account2); but got compilation error
*/
}
}
Do you know how can I fix the problem? What should I do so that to have multiple bank accounts associated to the same client?
Thanks in advance
George
Checkout this code :
//Account
public class Account
{
private int balance;
private String accNo;
public Account(int money,String num) {
balance = money;
accNo = num;
}
public int getBalance() {
return balance;
}
public void setBalance(int balance) {
this.balance = balance;
}
public String getAccNo() {
return accNo;
}
public void setAccNo(String accNo) {
this.accNo = accNo;
}
}
//Client
import java.util.ArrayList;
import java.util.Collection;
public class Client
{
private String clientName;
private HashSet<Account> accounts;
public Client(String name)
{
this.clientName = name;
this.accounts = new HashSet<Account>();
}
public void addAccount(Account account) {
accounts.add(account);
}
public String getClientName() {
return clientName;
}
public void setClientName(String clientName) {
this.clientName = clientName;
}
public Collection<Account> getAccounts() {
return accounts;
}
public void setAccounts(HashSet<Account> accounts) {
this.accounts = accounts;
}
public void printAccountDetails() {
System.out.println("Account details :");
int counter= 0;
for(Account acc : accounts) {
counter ++;
System.out.println("Account details for Account '"+counter+"' :\n");
System.out.println("Account Number : "+ acc.getAccNo() +" Balance :" + acc.getBalance() );
}
}
}
// Bank class
public class BankMain {
public static void main(String[] args)
{
Account account1 = new Account(1000,"11223A");
Account account2 = new Account(10000,"11111A");
Client client = new Client("George");
client.addAccount(account1);
client.addAccount(account2);
client.printAccountDetails();
}
}
Here you can add accounts as many as you want.
You can have multiple accounts for one client changing the data type in the Client class. For example:
private Map<String, Account> accounts;
Where the key of the map is the account number, and the value is the account itself. This way you can access each account by its unique number.
(If you don't know what a map is, check this)
This also means you need to either modify the Client constructor to accept multiple accounts or add a new method to add a new account to a Client.
As #m0skit0 suggested, use a map or list to hold Account object(s) under Client class.
public class Client
{
private String name;//name of the client
private List<Account> accounts = new ArrayList<Account>();
public Client(String nom, Account c)
{
name = nom;
accounts.add (c);
}
public boolean addAccount (Account c)
{
return accounts.add (c);
}
public removeAccount (Account c)
{
final int accountIndex = accounts.indexOf (c);
if (accountIndex > 0)
{
accounts.remove (accountIndex);
return true;
}
return false;
}
public void printName()
{
System.out.println("Name: " + name);
System.out.println ("Total Accounts: " + accounts.size());
for (int i=0; i<accounts.size(); i++)
{
final Account a = accounts.get(i);
System.out.println ("\tAccount Number: " + a.printAccountNumber());
System.out.println ("\tAccount Balance: " + a.printBalance());
}
}
}
And to use it in your BankMain.java
Account account1 = new Account(1000,"11223A");
Account account2 = new Account(10000,"11111A");
Client client1 = new Client("George", account1);
client1.addAccount (account2);
client1.printName();
Instead of trying to redefine client1 and 2 again like:
Client client1 = new Client("George",account1);
Client client1 = new Client("Oliver", account2);
redefine those object as:
client1 = new Client("George",account1);
...
client1 = new Client("Oliver", account2);
But doing so, you could operate on the same account i.e. if you now do client1.withdraw, you would withdraw from Oliver's account and not George.
Instead of doing so, you could maintain the name and account object in a map and given the name you can always fetch the account for that person. Like:
Map<String, Account> nameAccountMap = ..
And then you add corresponding accounts to it like:
nameAccountMap.put("Oliver", account2);
nameAccountMap.put("George",account1);
Now if you wish to operate on account owned by Oliver, you could do so by:
nameAccountMap.get("Oliver").withdraw...
And similar operations on other account holders.
If you wish to associate multiple accounts with a user, you could maintain map with name and list of accounts held by a user like:
Map<String, List<Account>> nameAccountMap = ..
Instead of having a single Account in your Client class, have a Set<Account> so as to have one to many relationship. Ensure that the Account class has equals and hashcode implemented.
public class Client
{
private String name;//name of the client
private Set<Account> accounts;
//the account associated to the client. Probably I should change sth here
// but I don't know what
public Client(String nom, Set<Account> c)
{
name = nom;
account = c;
}
public String getName()
{
return this.name;
}
public Set<Account> getAccounts()
{
return this.accounts;
}
public String toString()
{
...
// Return description of the Object state
}
}
public class Account
{
private int balance;
private String NumAccount; //each bank account has a unique number
public Account(int money,String num)
{
balance = money;
NumAccount = num;
}
public String getAccountNumber()
{
return NumAccount;
}
public boolean equals(..)
{
...
}
public int hashcode()
{
...
}
public String toString()
{
...
// Return description of the Object state
}
// below are the methods for withdraw,deposit- they are working properly
}
Related
private HashMap<Integer, Account> accountMap;
There are account objects inside this map.
What i am trying to do is merging objects by their key lets say add Account 2 object to Account 1 and remove Account 2 from map.
This method is in bank class:
public void combineAccounts(int uid1, int uid2) {
Account x = new Account(uid1);
x.add(accountMap.get(uid1),accountMap.get(uid2));
}
Account.class:
a1.getValuables returns list obj : [Value: 16253.0 -> 100.0gr gold]
public class Account{
private final int uid;
private final List<Valuable> valuables;
public Account(int uid) {
this.uid = uid;
valuables = new ArrayList<>();
}
public void addValuable(Valuable valuable){
valuables.add(valuable);
}
/*implementation of getTotalValue method comes here*/
public double getTotalValue​(){
return 0;
//returns total amount of valuables present in that account
}
public Account add(Account a1,Account a2){
Account mergedaccount;
mergedaccount = a1.getValuables()+a2.getValuables() // something like this...
return mergedaccount;
}
public int getUid() {
return uid;
}
public List<Valuable> getValuables() {
return valuables;
}
public void sortValuables(){
Collections.sort(valuables);
}
#Override
public String toString() {
return "uid:" + uid + " " + valuables;
}
}
Bank.class:
public class Bank {
private HashMap<Integer, Account> accountMap;
private Account merged;
public Bank() {
accountMap = new HashMap<>();
}
/*implementation of createAccount method comes here*/
public void createAccount(int uid){
for (HashMap.Entry<Integer, Account> entry : accountMap.entrySet()) {
if(entry.getKey() == uid){
throw new IllegalArgumentException();
}
}
accountMap.put(uid,new Account(uid));
// creates an account of id uid, if that account already exists an exception is thrown
}
public Account getAccount(int uid){
return accountMap.get(uid);
}
#Override
public String toString() {
Collection<Account> accounts = accountMap.values();
return accounts.toString();
}
public void addValuable(int uid, Valuable valuable) {
if(accountMap.get(uid) ==null){
System.out.println("valuables could not be added, no such account");
return;
}else{
accountMap.get(uid).addValuable(valuable);
}
//Add valuable to an existing account, if the account does not exist, an error message should be printed.
}
public void combineAccounts(int uid1, int uid2) {
Account x = new Account(uid1);
x.add(accountMap.get(uid1),accountMap.get(uid2));
}
public void closeAccount(int uid) {
if(accountMap.get(uid) != null){
accountMap.remove(uid);
}else{
throw new IllegalArgumentException();
}
}
}
I have the 3 classes below but for some reason I cannot display the transaction type and amount, I also cannot output the transaction history
CurrentAccount c1 = new CurrentAccount("234555",1000, 234, TransactionType.Deposit); // the part in bold is not displayed
see the output below:
234545 account number 100 overdraft.System.Collections.ArrayList Transaction history.
how could I correct my classes to display the transaction history correctly?
Please see below full classes
abstract class BankAccount
{
protected string AccountNumber { get; } // read property
protected double Balance { get; set; } //read and write property
public BankAccount(string _accountNumber)
{
this.AccountNumber = _accountNumber;
this.Balance = 0;
}
public virtual void MakeDeposit(double amount)
{
Balance = Balance + amount;
}
public virtual void MakeWithdraw(double amount)
{
Balance = Balance - amount;
}
}
}
class CurrentAccount : BankAccount
{
private double OverdraftLimit { get; } // read only property
public ArrayList TransactionHistory = new ArrayList();
public CurrentAccount(string AccountNumber, double OverdraftLimit, double amount, TransactionType type) : base(AccountNumber)
{
this.OverdraftLimit = OverdraftLimit;
TransactionHistory.Add(new AccountTransaction(type, amount));
}
public override void MakeDeposit(double amount) // override method
{
Balance += amount;
TransactionHistory.Add(new AccountTransaction(TransactionType.Deposit, amount));
}
public override void MakeWithdraw(double amount)
{
if (Balance + OverdraftLimit > 0)
{
Balance -= amount;
TransactionHistory.Add(new AccountTransaction(TransactionType.Withdrawal, amount));
}
else
{
throw new Exception("Insufficient Funds");
}
}
public override string ToString()
{
// print the transaction history too
return AccountNumber + " account number " + OverdraftLimit + " overdraft." + TransactionHistory + " Transaction history.";
}
}
}
{
enum TransactionType
{
Deposit, Withdrawal
}
class AccountTransaction
{
public TransactionType type { get; private set; } // deposit/withdrawal
private double Amount { get; set; }
public AccountTransaction (TransactionType type, double _amount)
{
this.type = type;
this.Amount = _amount;
}
public override string ToString()
{
return "type" + type + "amount" + Amount;
}
}
}
class Program
{
static void Main(string[] args)
{
CurrentAccount c1 = new CurrentAccount("234555",1000, 234, **TransactionType.Deposit)**; // this part is not displayed
CurrentAccount c2 = new CurrentAccount("234534", 12000, 345, **TransactionType.Withdrawal)**; // this part is not displayed
CurrentAccount c3 = new CurrentAccount("234545", 100, 456, **TransactionType.Withdrawal)**; // this part is not displayed
Console.WriteLine(c1);
Console.WriteLine(c2);
Console.WriteLine(c3);
}
}
}
Output from the console:
234555 account number 1000 overdraft.System.Collections.ArrayList Transaction history.
234534 account number 12000 overdraft.System.Collections.ArrayList Transaction history.
234545 account number 100 overdraft.System.Collections.ArrayList Transaction history.
Please could you help me to output the correct information.
I don't know why this is happening bevause you have the string method override. The only thing that I though is that you need to override tostring method in bank class to because you are inheriting from bank. Try it and tell to me if this works.
I have Five Classes:
BankApp:
public class BankApp {
public static void main(String[] args) {
BankDatabase acctDatabase = new BankDatabase();
acctDatabase.createCheckingAccount("Test Name", "123-45-6789", 20000.0f);
acctDatabase.applyInterest();
acctDatabase.print();
}
}
BankDatabase:
import java.util.ArrayList;
import java.util.Collections;
public class BankDatabase {
ArrayList<BankAccount> list = new ArrayList<>();
public void createCheckingAccount(String name, String ssn, float bal) {
BankAccount account = new CheckingAccount(name, ssn, bal);
list.add(account);
}
public void createSavingsAccount(String name, String ssn, float bal) {
BankAccount account = new SavingsAccount(name, ssn, bal);
list.add(account);
}
public void print() {
Collections.sort(list, (BankAccount a, BankAccount b) -> {
return Float.compare(b.bal, a.bal);
});
for(int i = 0; i < list.size(); i++)
System.out.println(list.get(i));
}
public abstract void applyInterest();
}
BankAccount:
public abstract class BankAccount {
protected String name;
protected String ssn;
protected float bal;
private String account;
public BankAccount(String name, String ssn, float bal) {
name = this.name;
ssn = this.ssn;
bal = this.bal;
accountNumber();
System.out.println("Successfully created account for " + name + ". Account Number: " + account);
if(!ssn.matches("^(\\d{3}-?\\d{2}-?\\d{4})$")) {
System.out.println(name + " has an invalid SSN!");
}
System.out.println(name + ", Balance $" + bal);
}
#Override
public String toString() {
return "Name: " + name + ", Account #: " + account + ", Balance: $" + bal;
}
public abstract void applyInterest();
}
CheckingAccount:
public class SavingsAccount extends BankAccount {
public SavingsAccount(String name, String ssn, float bal) {
super(name, ssn, bal);
}
#Override
public void applyInterest() {
bal = (float) (bal * 1.05);
}
}
and SavingsAccount:
public class CheckingAccount extends BankAccount {
public CheckingAccount(String name, String ssn, float bal) {
super(name, ssn, bal);
}
#Override
public void applyInterest() {
if(bal >= 10000.00) {
bal = (float) ((bal - 10000.00) * 1.02) + 10000;}
}
}
}
I want to call applyInterest() from BankApp but, I can't because BankDatabase is not abstract. I can't make BankDatabase abstract because if I do, then I couldn't instantiate BankDatabase. So, my question is: how do I call applyInterest()?
That method in BankDatabase should not be abstract. I think you want to do this:
public class BankDatabase {
private List<BankAccount> accounts = new ArrayList<>();
// Add a BankAccount; leave the type creation outside this method.
// Polymorphism is your friend; use it.
public void addAccount(BankAccount account) {
if (account != null) {
this.accounts.add(account);
}
}
public void applyInterest() {
for (BankAccount account : this.accounts) {
account.applyInterest();
}
}
}
A few other points:
Think about an AccountFactory for creating savings or checking accounts (aka virtual constructor)
Magic numbers are a very bad idea. Take those constants out of your accounts and make them variable. Interest rates change, don't they?
You need a method to return the BankAccount you're trying to apply the interest to.
So, in your list of BankAccounts you need to find the account.
Seach by ID or name. From there, you call a search method on your list to return the bank account, and from that you can .applyInterest to it.
I am creating a project that allows a user to create, delete or display bank accounts and to deposit, withdraw or print transactions.
I don't know how to deposit, withdraw, print transactions using the scanner when the user provides the account id.
main:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
BankProcess bankProcess = new BankProcess();
TransactionProcess transactionProcess = new TransactionProcess();
Bank bank = new Bank();
BankAccount bankAccount = new BankAccount();
int input = 0;
int selection = 0;
while (input == 0) {
System.out.println("");
System.out.println("Please choose one of the following: ");
System.out.println("[1] Create an account");
System.out.println("[2] Print all existing accounts");
System.out.println("[3] Delete an account");
System.out.println("[4] Deposit");
System.out.println("[5] Withdraw");
System.out.println("[6] Print transactions");
System.out.println("[0] Exit");
selection = scan.nextInt();
switch (selection) {
case 0:
System.out.println("Exit Successful");
System.exit(0);
case 1:
System.out.println("'[1] Create an account' has been selected.");
System.out.print("Account Id: ");
int accountId = scan.nextInt();
scan.nextLine();
System.out.print("Holder Name: ");
String holderName = scan.nextLine();
System.out.print("Holder Address: ");
String holderAddress = scan.nextLine();
System.out.print("Opening Balance: ");
double openingBalance = scan.nextDouble();
System.out.print("Open Date: ");
String openDate = scan.next();
bankAccount = new BankAccount(accountId, holderName, openingBalance, holderAddress, openDate);
bank.setAccounts(bankProcess.openNewAccount(bank.getAccounts(), bankAccount));
System.out.println("Successfully Added.");
break;
case 2:
System.out.println("'[2] Display all existing accounts' has been selected");
System.out.println("-----------------------------------------------------");
bank.getAccounts().forEach((i, b) - > System.out.println(b));
System.out.println("-----------------------------------------------------");
break;
case 3:
System.out.println("[3] Delete an account has been selected");
System.out.println("Enter the account ID: ");
bank.removeAccounts(bankProcess.openNewAccount(bank.getAccounts(), bankAccount));
break;
case 4:
System.out.println("[4] Deposit has been selected");
break;
case 5:
System.out.println("[5] Withdraw has been selected");
break;
case 6:
System.out.println("[6] Print Transaction has been selected");
break;
default:
System.out.println("Your choice was not valid!");
}
}
}
class Bank
public class Bank {
private TreeMap < Integer, BankAccount > bankAccounts = new TreeMap < Integer, BankAccount > ();
public TreeMap < Integer, BankAccount > getAccounts() {
return bankAccounts;
}
public void setAccounts(TreeMap < Integer, BankAccount > accounts) {
this.bankAccounts = accounts;
}
public void removeAccounts(TreeMap < Integer, BankAccount > accounts) {
this.bankAccounts = accounts;
}
}
class BankProcess
public class BankProcess {
// return the Updated list of BankAccounts
public TreeMap < Integer, BankAccount > openNewAccount(TreeMap < Integer, BankAccount > bankAccounts, BankAccount bankAccount) {
//Get the List of existing bank Accounts then add the new BankAccount to it.
bankAccounts.put(bankAccount.getAccountId(), bankAccount);
return bankAccounts;
}
public TreeMap < Integer, BankAccount > removeAccount(TreeMap < Integer, BankAccount > bankAccounts, BankAccount bankAccount) {
bankAccounts.remove(bankAccount.getAccountId(), bankAccount);
return bankAccounts;
}
}
class BankAccount
public class BankAccount {
private int accountId;
private String holderName;
private String holderAddress;
private String openDate;
private double currentBalance;
private List < Transaction > transactions = new ArrayList < Transaction > ();
//Provide Blank Constructor
public BankAccount() {}
//Constructor with an arguments.
public BankAccount(int accountNum, String holderNam, double currentBalance, String holderAdd, String openDate) {
this.accountId = accountNum;
this.holderName = holderNam;
this.holderAddress = holderAdd;
this.openDate = openDate;
this.currentBalance = currentBalance;
}
// Always Provide Setter and Getters
public int getAccountId() {
return accountId;
}
public void setAccountId(int accountId) {
this.accountId = accountId;
}
public String getHolderName() {
return holderName;
}
public void setHolderName(String holderName) {
this.holderName = holderName;
}
public String getHolderAddress() {
return holderAddress;
}
public void setHolderAddress(String holderAddress) {
this.holderAddress = holderAddress;
}
public String getOpenDate() {
return openDate;
}
public void setOpenDate(String openDate) {
this.openDate = openDate;
}
public double getCurrentBalance() {
return currentBalance;
}
public void setCurrentBalance(double currentBalance) {
this.currentBalance = currentBalance;
}
public List < Transaction > getTransactions() {
return transactions;
}
public void setTransactions(List < Transaction > transactions) {
this.transactions = transactions;
}
public String toString() {
return "\nAccount number: " + accountId + "\nHolder's name: " + holderName + "\nHolder's address: " + holderAddress + "\nOpen Date: " + openDate + "\nCurrent balance: " + currentBalance;
}
}
class Transaction
public class Transaction {
private int transactionId;
private String transactionType;
private double transactionAmount;
private double moneyBeforeTransaction;
private double moneyAfterTransaction;
public Transaction() {}
public Transaction(int transactionId, String transactionType, double transactionAmount, double moneyBeforeTransaction) {
this.transactionId = transactionId;
this.transactionType = transactionType;
this.transactionAmount = transactionAmount;
this.moneyBeforeTransaction = moneyBeforeTransaction;
}
public int getTransactionId() {
return transactionId;
}
public void setTransactionId(int transactionId) {
this.transactionId = transactionId;
}
public String getTransactionType() {
return transactionType;
}
public void setTransactionType(String transactionType) {
this.transactionType = transactionType;
}
public double getTransactionAmount() {
return transactionAmount;
}
public void setTransactionAmount(double transactionAmount) {
this.transactionAmount = transactionAmount;
}
public double getMoneyBeforeTransaction() {
return moneyBeforeTransaction;
}
public void setMoneyBeforeTransaction(double moneyBeforeTransaction) {
this.moneyBeforeTransaction = moneyBeforeTransaction;
}
public double getMoneyAfterTransaction() {
return moneyAfterTransaction;
}
public void setMoneyAfterTransaction(double moneyAfterTransaction) {
this.moneyAfterTransaction = moneyAfterTransaction;
}
//Override the toString() method of String ?
public String toString() {
return "Transaction ID : " + this.transactionId +
" Transaction Type : " + this.transactionType +
" Transaction Amount : " + this.transactionAmount +
" Money Before Transaction : " + this.moneyBeforeTransaction +
" Money After Transaction : " + this.moneyAfterTransaction;
}
}
class TransactionProcess
public class TransactionProcess {
//Always Provide another class for process.
//Pass the bankAccount of the user
public void deposit(BankAccount bankAccount, double depositAmount) {
//Get the CurrentBalance
double currentBalance = bankAccount.getCurrentBalance();
//First Argument : set the Id of transaction
//Second Argument : set the Type of Transaction
//Third Argument : set the TransactionAmount
//Fourth Argument : set the Balance Before the transaction (for record purposes)
Transaction transaction = new Transaction(bankAccount.getTransactions().size(), "Deposit", depositAmount, currentBalance);
if (depositAmount <= 0) {
System.out.println("Amount to be deposited should be positive");
} else {
//Set the updated or transacted balance of bankAccount.
bankAccount.setCurrentBalance(currentBalance + depositAmount);
//then set the MoneyAfterTransaction
transaction.setMoneyAfterTransaction(bankAccount.getCurrentBalance());
//after the transaction add it to the list of Transaction of bankAccount
bankAccount.getTransactions().add(transaction);
}
}
// Explanation same as above
public void withdraw(BankAccount bankAccount, double withdrawAmount) {
double currentBalance = bankAccount.getCurrentBalance();
Transaction transaction = new Transaction(bankAccount.getTransactions().size(), "Withdraw", withdrawAmount, currentBalance);
if (withdrawAmount <= 0) {
System.out.println("Amount to be withdrawn should be positive");
} else {
if (currentBalance < withdrawAmount) {
System.out.println("Insufficient balance");
} else {
bankAccount.setCurrentBalance(currentBalance - withdrawAmount);
transaction.setMoneyAfterTransaction(bankAccount.getCurrentBalance());
bankAccount.getTransactions().add(transaction);
}
}
}
}
Operations like deposit or withdraw work almost the same way, so let's concentrate on deposit for now.
You already have the appropriate switch-case for that:
case 4: {
// deposit
break;
}
(by the way: the braces { and } are not mandatory here, they just help to isolate the code, so that it is easier to read)
Anyway; For deposing money on a bank account you need the account number first and then you need to get the account from the bank
case 4: {
int accountNumber = scan.nextInt(); // user types account number
TreeMap <Integer, BankAccount> bankAccounts = bank.getAccounts(); // bank returns all accounts (this is quite an insecure operation, it would be better to add a method to the bank class that returns only one account when passing the accountNumber
BankAccount bankAccount = bankAccounts.get(accountNumber);
break;
}
Using the method bank.getAccounts is not a good design here, as the method will return all accounts from the bank. It would be better to have a method in your class Bank that returns a single account.
public class Bank{
// ...
public BankAccount getAccount(Integer accountNumber){
return bankAccounts.get(accountNumber);
}
}
Because this will encapsulate the logic to retrieve one account to the Bank class. There you can also add some error handling logic, e.g. when the account number is not valid.
So, at this point you have the user's account and you know the user wants to deposit some money. You only have to ask how much he wants to deposit. Use the Scanner again to let the user type in an amount.
Now that you have your BankAccount and the amount you need to make a Transaction or better a TransactionProcess
TransactionProcess transactionProcess = new TransactionProcess(); // use the standard constructor to create an empty transactionProcess
transactionProcess.deposit(bankAccount, amount);
If I understand your program correctly, the method deposit will already use the user's BankAccount and add the money while creating a Transaction for the account. Am I correct? Then you are actually finished here.
Put that code together for switch-chase 4 and if it works use a similar logic to implement withdraw.
I hope this helps!
// Edit // to answer your other question, this is what I had in mind:
in your BankAccount class add a method like this one:
public void addTransaction(Transaction transaction){
if(transactions.size() >= 6){ // test if the list has 6 or more transactions saved
transactions.remove(0); // if so, then remove the first (it's the oldest)
}
transactions.add(transaction); // the new transaction is always added, no matter how many other transactions there are already in the list
}
This is just an example, but I think you should be able to control the amount of transactions per Bank account like this. In addition you can now simplify the call: have a look at the last line of your deposit method in your TransactionProcess class. There you call
bankAccount.getTransactions().add(transaction); // takes the bank account, retrieves the list of transactions from the bank account and adds a transaction to the list
with the new method addTransaction you could now write it like this instead:
bankAccount.addTransaction(transaction); // adds a transaction to the bank account
Much cleaner, don't you think? And now you can put all your logic for managing and adding transactions in that new method :)
I am trying to create mutliple objects of a type of class I made. I then want to transfer these values into the array list. How can I create objects using a while loop that have different names. For example here is my code now, but it would only make an object of one name.
Customer cust = new Customer("bob", 20.0);
and my constructor if you want to see:
public Customer(String customerName, double amount)
{
String name=customerName;
double sale=amount;
}
StoreTest class (with main method):
import java.util.ArrayList;
import java.util.Scanner;
public class StoreTest {
ArrayList<Customer> store = new ArrayList<Customer>();
public static void main (String[] args)
{
double sale=1.0; //so the loop goes the first time
//switch to dowhile
Scanner input = new Scanner(System.in);
System.out.println("If at anytime you wish to exit" +
", please press 0 when asked to give " +
"sale amount.");
while(sale!=0)
{
System.out.println("Please enter the " +
"customer's name.");
String theirName = input.nextLine();
System.out.println("Please enter the " +
"the amount of the sale.");
double theirSale = input.nextDouble();
store.addSale(theirName, theirSale);
}
store.nameOfBestCustomer();
}
}
Customer class:
public class Customer {
private String name;
private double sale;
public Customer()
{
}
public Customer(String customerName, double amount)
{
name=customerName;
sale=amount;
}
}
Store class (has methods for messing with arraylist:
import java.util.ArrayList;
public class Store {
//creates Customer object and adds it to the array list
public void addSale(String customerName, double amount)
{
this.add(new Customer(customerName, amount));
}
//displays name of the customer with the highest sale
public String nameOfBestCustomer()
{
for(int i=0; i<this.size(); i++)
{
}
}
}
ArrayList<Customer> custArr = new ArrayList<Customer>();
while(youWantToContinue) {
//get a customerName
//get an amount
custArr.add(new Customer(customerName, amount);
}
For this to work... you'll have to fix your constructor...
Assuming your Customer class has variables called name and sale, your constructor should look like this:
public Customer(String customerName, double amount) {
name = customerName;
sale = amount;
}
Change your Store class to something more like this:
public class Store {
private ArrayList<Customer> custArr;
public new Store() {
custArr = new ArrayList<Customer>();
}
public void addSale(String customerName, double amount) {
custArr.add(new Customer(customerName, amount));
}
public Customer getSaleAtIndex(int index) {
return custArr.get(index);
}
//or if you want the entire ArrayList:
public ArrayList getCustArr() {
return custArr;
}
}
You can use this code...
public class Main {
public static void main(String args[]) {
String[] names = {"First", "Second", "Third"};//You Can Add More Names
double[] amount = {20.0, 30.0, 40.0};//You Can Add More Amount
List<Customer> customers = new ArrayList<Customer>();
int i = 0;
while (i < names.length) {
customers.add(new Customer(names[i], amount[i]));
i++;
}
}
}