I am a bit stuck on this one. I am writing a java program with two classes, and then a test program to test the methods in the class. I am stuck on calling the two methods below in the main method. All of the class files (the test program class and the two other classes) are compiling and the IDE is not giving me any error messages, the calculation is just not occurring...
--Main Method Code:
//Call debit method
System.out.println("Please enter amount to be debited");
double amount=input.nextDouble();
account.debit(amount);
System.out.printf("%.2f%n",balance);
//Call credit method
System.out.println("Please enter amount to be credited");
amount=input.nextDouble();
account.credit(amount);
System.out.printf("%.2f%n",balance);
--Account Class Code:
//Method for crediting account balance
public void credit (double amount) {
double newBalance=this.balance+amount;
this.setBalance(newBalance);
}
//Method for debiting account balance
public void debit (double amount) {
if (amount<balance) {
double newBalance=this.balance-amount;
this.setBalance(newBalance);
} else {
System.out.println("Insufficient Funds!");
}
NOTE: the balance setter is working, as it is called earlier in the test program...
Any help much appreciated!!!
Complete Code for Account Class:
public class Account {
private int accountId;
private String accountName;
private String accountAddress;
private double balance;
private Bank bank;
//Default Constructor
public Account () {
}
//Getters
public int getAccountId () {
return accountId;
}
public String getAccountName () {
return accountName;
}
public String getAccountAddress () {
return accountAddress;
}
public double getBalance () {
return balance;
}
public Bank getBank () {
return bank;
}
//Setters
public void setAccountId (int accountId) {
if (accountId <=10000000 || accountId >=99999999) {
System.out.println("Invalid Account Id");
} else {
this.accountId=accountId;
}
}
public void setAccountName (String accountName) {
if (accountName.length()>=10) {
System.out.println("Too Long");
} else {
this.accountName=accountName;
}
}
public void setAccountAddress (String accountAddress) {
this.accountAddress=accountAddress;
}
public void setBalance (double balance) {
if (balance<0.0) {
System.out.println("Invalid Balance");
} else {
this.balance=balance;
}
}
public void setBank (Bank bank) {
this.bank=bank;
}
//Constructor to initialize accountId, accountName, accountAddress and Bank
public Account (int accountId, String accountName, String accountAddress, Bank bank) {
this.setAccountId(accountId);
this.setAccountName(accountName);
this.setAccountAddress(accountAddress);
this.setBank(bank);
}
//Method to print out account category based on balance
public void printAccountCategory () {
if (balance<100.0) {
System.out.println("Challenged Account");
} else if (balance>=100.0 && balance<999.9) {
System.out.println("Standard Account");
} else if (balance>=1000.0 && balance<9999.9) {
System.out.println("Promising Account");
} else if (balance>=10000.0 && balance<99999.9) {
System.out.println("Gold Star Account");
} else {
System.out.println("Super Duper Account");
}
}
//Method to project balance based on compound interest and the number of years required
//Note: I took the formula using n (number of times the interest is compounded per year) as 1
public double projectNewBalance (int numberYears) {
if (numberYears>0) {
double interest=1;
for (int i=1; i<=numberYears; i++) {
interest*=(1.0+bank.getInterestRate());
}
double newBalance=balance*interest;
return newBalance;
} else if (numberYears<0) {
System.out.println("Invalid Value");
} else {
return balance;
}
return balance;
}
//Method for crediting account balance
public void credit (double amount) {
double newBalance=this.balance+amount;
this.setBalance(newBalance);
}
//Method for debiting account balance
public void debit (double amount) {
if (amount<balance) {
double newBalance=this.balance-amount;
this.setBalance(newBalance);
} else {
System.out.println("Insufficient Funds!");
}
}
//toString method
public String toString () {
return "Account Id: "+accountId+", Account Name: " + accountName + ", Account Address: "+accountAddress+", Balance: "+balance+", Bank Details: "+bank.toString()+".";
}
}
Main Method Full Code:
import java.util.Scanner;
public class BankAccountTest {
public static void main (String [ ] args) {
//Create an instance of the Bank class
Bank bank = new Bank ("WIT Bank", "Paddy Snow", 0.045);
//Create instance of Scanner class
Scanner input=new Scanner(System.in);
//Prompt user to input data to create an account
System.out.println("Please enter an Account ID");
int accountId=input.nextInt();
System.out.println("Please enter an Account Name");
String accountName=input.next();
System.out.println("Please enter an Account Address");
String accountAddress=input.next();
//Create instance of the Account class
Account account = new Account (accountId, accountName, accountAddress, bank);
//Print out details of account class
System.out.println(account);
//Prompt user to enter balance for the account
System.out.println("Please enter account balance");
double balance=input.nextDouble();
account.setBalance(balance);
//Use printAccountCategory method
account.printAccountCategory();
//Call projectNewBalance method
// Note: Method tested with value of 10 years as mentioned in spec,
// but user input also included I think it is more appropriate for the functionality of the program
// int numberYears=10;
// double newBalance1=account.projectNewBalance(numberYears);
// System.out.println(""+newBalance1);
System.out.println("Please enter number of years");
int numberYears=input.nextInt();
double newBalance=account.projectNewBalance(numberYears);
System.out.printf("%.2f%n",newBalance);
//Call debit method
System.out.println("Please enter amount to be debited");
double amount=input.nextDouble();
account.debit(amount);
System.out.printf("%.2f%n",balance);
//Call credit method
System.out.println("Please enter amount to be credited");
amount=input.nextDouble();
account.credit(amount);
System.out.printf("%.2f%n",balance);
}
}
Your numbers might always look the same because the local variable is not being updated before printing it out.
Make sure you update the value of balance before your call to System.out.printf("%.2f%n",balance);.
Something like:
balance = account.getBalance();
Shouldn't it be printing the balance of the object you have created and not just "balance":
System.out.println(account.getBalance())?
Related
I'm messing around with inheritance and confused on how to do a few different things. Here is what I have:
Looking at the Account class and write a main method in a different class Bank to brief experiment with some instances of the Account class.
Using the Account class as a base class, write two derived classes called SavingsAccount and CheckingAccount. A SavingsAccount object, in addition to the attributes of an Account object, should have an interest variable and a method which adds interest to the account. A CheckingAccount object, in addition to the instance variables of an Account object, should have an overdraft limit variable. Ensure that you have overridden methods of the Account class as necessary in both derived classes.
Now create a Bank class, an object of which contains an array of Account objects. Accounts in the array could be instances of the Account class, the SavingsAccount class, or the CheckingAccount class. Create some test accounts (some of each type).
Write an update method in the bank class. It iterates through each account, updating it in the following ways: Savings accounts get interest added (via the method you already wrote); Checking Account get a letter sent if they are in overdraft.
public class Account {
private double balance;
private int acctNum;
public Account (int num)
{
balance = 0.0;
acctNum = num;
}
public void deposit (double amt)
{
if (amt >0)
balance +=amt;
else
System.out.println("Account.deposit(...): "
+"cannot deposit negative amount.");
}
public void withdraw (double amt)
{
if (amt>0)
balance -=amt;
else
System.err.println("Account.withdraw(...): "
+"cannot withdraw negative amount.");
}
public double getBalance()
{
return balance;
}
public double getAccountNumber()
{
return acctNum;
}
public String toString()
{
return "Acc " + acctNum + ": " + "balance = "+ balance;
}
public final void print()
{
System.out.println( toString());
}
}
Now the SavingsAccount
public class SavingsAccount extends Account {
private double interest;
public SavingsAccount(int acctNum, double interest) {
super(acctNum);
this.interest=interest;
}
public double getInterest() {
double x= getBalance() + getBalance()*interest;
return x;
// public void setInterest((interest))
// this.interest=interest;
}
public void AddInterest (double interest) {
double x = super.getBalance() * interest;
super.deposit(x);
}
public String toString() {
return super.toString()+" Interest : " + interest;
}
}
CheckingAccount
public class CheckingAccount extends Account {
private double limit;
public CheckingAccount(int acctNum, double limit) {
super(acctNum);
this.limit=limit;
}
public double getLimit() {
return this.limit;
}
public void setLimit(double limit) {
this.limit=limit;
}
public void withdraw (double limit) {
if (limit <= this.limit)
super.withdraw(limit);
else {
System.out.println(" Sorry, Limit Exceeded" );
}
}
public String toString() {
return super.toString() +"Limit : "+limit;
}
}
Bank class
public class Bank {
public static void main(String[] args) {
Account[] accounts = new Account[2];
accounts[0] = new SavingsAccount(2, 0.25);
accounts[1] = new CheckingAccount(23, 50);
for(int i=0; i<accounts.length;i++) {
if (accounts[0].equals(SavingsAccount)
System.out.println(accounts[0].getInterest());
}
}
So here is my problems that I am noticing.
In the SavingsAccount I'm not sure how to get the setInterest() to work. I have tried changing it to a int, but then that changes the Account class. How do I get that to work properly?
In the bank class - the for loop I have written. Its not working, I have tried if(accounts[i].equals so so, but does not seem to function properly. What is the correct way?
As well, I'm assuming everything is coming from my SavingsAccount class.
If I understand what you are trying to do in your for-loop you need to use instanceof to check classes, not equals().
So, for example
Account[] accounts = new Account[2];
accounts[0] = new SavingsAccount(2, 0.25);
accounts[1] = new CheckingAccount(23, 50);
for(int i=0; i<accounts.length;i++) {
if (accounts[i] instanceof SavingsAccount) {
// You must cast an Account to use any of the descendant's methods
SavingsAccount account = (SavingsAccount) accounts[i];
System.out.println(account.getInterest());
} else { // it's a CheckingAccount
}
}
Other than that, StackOverflow is not a place for you to dump homework requirements, so your question is overly broad to answer in completion.
I'm a new user in stack overflow.. okay so I'm doing an ATM Java program.. my problem is, I'm having a hard time trying to figure out how to make a file reader (mine is customers.txt) in my ATMSimulator.java..
Here is my ATM.java :
/*
An ATM that accesses a bank.
*/
public class ATM
{
public static final int CHECKING = 1;
public static final int SAVINGS = 2;
private int state;
private int customerNumber;
private Customer currentCustomer;
private BankAccount currentAccount;
private Bank theBank;
public static final int START = 1;
public static final int PIN = 2;
public static final int ACCOUNT = 3;
public static final int TRANSACT = 4;
/*
Construct an ATM for a given bank.
#param aBank the bank to which this ATM connects
*/
public ATM (Bank aBank)
{
theBank = aBank;
reset();
}
/*
Resets the ATM to the initial state
*/
public void reset()
{
customerNumber = -1;
currentAccount = null;
state = START;
}
/*
Sets the current customer number and sets state to PIN.
(Precondition: state is START)
#param number the customer number
*/
public void setCustomerNumber (int number)
{
assert state == START;
customerNumber = number;
state = PIN;
}
/*
Finds customer in bank. If found, sets state to ACCOUNT, else to START
(Precondition: state is PIN)
#param pin the PIN of the current customer
*/
public void selectCustomer (int pin)
{
assert state == PIN;
currentCustomer = theBank.findCustomer (customerNumber, pin);
if (currentCustomer == null)
state = START;
else
state = ACCOUNT;
}
/*
Sets current account to checking or savings. Sets state to TRANSACT.
(Precondition: state is ACCOUNT or TRANSACT)
#param account one of CHECKING or SAVINGS
*/
public void selectAccount (int account)
{
assert state == ACCOUNT || state == TRANSACT;
if (account == CHECKING )
currentAccount = currentCustomer.getCheckingAccount ();
else
currentAccount = currentCustomer.getSavingsAccount();
state = TRANSACT;
}
/*
Withdraws amount from current account.
(Precondition state is TRANSACT)
#param value the amount to withdraw
*/
public void withdraw (double value)
{
assert state == TRANSACT;
currentAccount.withdraw(value);
}
/*
Deposits amount to current account.
(Prcondition: state is TRANSACT)
#param value the amount to deposit
*/
public void deposit (double value)
{
assert state == TRANSACT;
currentAccount.deposit (value);
}
/*
Gets the balance of the current account.
(Precondition: state is TRANSACT)
#return the balance
*/
public double getBalance()
{
assert state == TRANSACT;
return currentAccount.getBalance();
}
/*
Moves back to previous state
*/
public void back ()
{
if (state == TRANSACT)
state = ACCOUNT;
else if (state == ACCOUNT)
state = PIN;
else if (state == PIN)
state = START;
}
/*
Gets the current state of this ATM.
#return the currnt state
*/
public int getState ()
{
return state;
}
}
Here is my Customer.java :
/*
A bank customer with a checking and a savings account.
*/
public class Customer
{
private int customerNumber;
private int pin;
private BankAccount checkingAccount;
private BankAccount savingsAccount;
/*
Construct a customer with a given number and PIN.
#param aNumber the customer number
#param aPin the personal identification number
*/
public Customer (int aNumber, int aPin)
{
customerNumber = aNumber;
pin = aPin;
checkingAccount = new BankAccount();
savingsAccount = new BankAccount();
}
/*
Test if this customer matches a customer number and PIN
#param aNumber a customer number
#param aPin a personal identification number
#return true if the customer number and PIN match
*/
public boolean match (int aNumber, int aPin)
{
return customerNumber == aNumber && pin == aPin;
}
/*
Gets the checking account of this customer
#return the checking account
*/
public BankAccount getCheckingAccount()
{
return checkingAccount;
}
/*
Get the savings account of this customer
#return checking account
*/
public BankAccount getSavingsAccount()
{
return savingsAccount;
}
}
Here is my Bank.java :
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
/*
A bank contains customer with bank accounts
*/
public class Bank
{
private ArrayList<Customer> customers;
/*
Construct a bank with no customers
*/
public Bank()
{
customers = new ArrayList<Customer> ();
}
/*
Reads the customer numbers and pins
and initializes the bank accounts
#param filename the name of the customer file
*/
public void readCustomers(String filename)
throws IOException
{
Scanner in = new Scanner (new File(filename));
while (in.hasNext())
{
int number = in.nextInt();
int pin = in.nextInt();
Customer c = new Customer (number, pin);
addCustomer (c);
}
in.close();
}
/*
Adds a customer to the bank.
#param c the customer to add
*/
public void addCustomer (Customer c)
{
customers.add(c);
}
/*
Find a customer in the bank.
#param aNumber a customer number
#param aPin a personal identification number
#return the matching customer, or null if no customer matches
*/
public Customer findCustomer (int aNumber, int aPin)
{
for (Customer c : customers)
{
if (c.match(aNumber, aPin))
return c;
}
return null;
}
}
Here is my BankAccount.java :
/**
A bank account has a balance that can be changed by deposits and withdrawals
*/
public class BankAccount
{
private int accountNumber;
private double balance;
/**
Counstruct a bank account with a zero balance.
#param anAccountNumber the account number for this account
*/
public BankAccount(){}
public BankAccount(int anAccountNumber)
{
accountNumber = anAccountNumber;
balance = 0;
}
/**
Construct a bank account with a given balance.
#param anAccountNumber the account number for this account
#param initialBalance the initial balance
*/
public BankAccount(int anAccountNumber, double initialBalance)
{
accountNumber = anAccountNumber;
balance = initialBalance;
}
/**
Gets the account number of this bank account.
#return the account number
*/
public int getAccountNumber()
{
return accountNumber;
}
/**
Deposits money into bank account
#param amount the amount to deposit
*/
public void deposit (double amount)
{
double newBalance = balance + amount;
balance = newBalance;
}
/**
Withdraws money from the bank account.
#param amount the amount to withdraw
*/
public void withdraw(double amount)
{
double newBalance = balance - amount;
balance = newBalance;
}
/**
Gets the current balance of the bank account.
#return the current balance
*/
public double getBalance()
{
return balance;
}
}
And I'm having a problem with customers.txt in ATMSimulator.java:
import java.io.IOException;
import java.util.Scanner;
/*
A text based simulation of an automatic teller machine.
*/
public class ATMSimulator
{
public static void main (String [] args)
{
ATM theATM;
try
{
Bank theBank = new Bank ();
theBank.readCustomers("customers.txt");
theATM = new ATM (theBank);
}
catch (IOException e)
{
System.out.println ("Error opening accounts file.");
return;
}
Scanner in= new Scanner (System.in);
while (true)
{
int state = theATM.getState();
if (state == ATM.START)
{
System.out.print ("Enter customer number: ");
int number = in.nextInt();
theATM.setCustomerNumber(number);
}
else if (state == ATM.PIN)
{
System.out.println ("Enter PIN: ");
int pin = in.nextInt();
theATM.setCustomerNumber (pin);
}
else if (state == ATM.ACCOUNT )
{
System.out.print ("A = Checking, B = Savings, C = Quit: ");
String command = in.next();
if (command.equalsIgnoreCase ("A"))
theATM.selectAccount (ATM.CHECKING);
else if (command.equalsIgnoreCase ("B"))
theATM.selectAccount (ATM.SAVINGS);
else if (command.equalsIgnoreCase ("C"))
theATM.reset();
else
System.out.println ("Illegal input!");
}
else if (state == ATM.TRANSACT)
{
System.out.println ("Balance = " + theATM.getBalance());
System.out.print ("A = Deposit, B = Withdrawal, C = Cancel: ");
String command = in.next();
if (command.equalsIgnoreCase ("A"))
{
System.out.print ("Amount: ");
double amount = in.nextDouble();
theATM.deposit (amount);
theATM.back();
}
else if (command.equalsIgnoreCase ("B"))
{
System.out.print ("Amount: ");
double amount = in.nextDouble();
theATM.withdraw (amount);
theATM.back();
}
else if (command.equalsIgnoreCase ("C"))
theATM.back();
else
System.out.println ("Illegal input!");
}
}
}
}
I had created the customers.txt file, but the output is error.. please help me
I'll address your question not the sh.. big amount of code.
You efficiently read from file in this way.
try( BufferedReader br = new BufferedReader(new FileReader("filename.txt"))){
String line;
while((line = br.readLine()) != null){
}
}catch(IOException e}{
e.printStackTrace();
}
If you wish to read from console:
try( BufferedReader br = new BufferedReader(new InputStreamReader(System.in))){
String line;
while((line = br.readLine()) != null){
}
}catch(IOException e}{
e.printStackTrace();
}
To indicate the end of input in the console use ctrl + z.
Hey so the path for the text file you passed in the method readCustomer is not the right path. So what you can do is put in src and package name in the path as follows: "src/packageName/customer.txt"
so when you call it in your main it would be
public static void main (String [] args)
{
ATM theATM;
try
{
Bank theBank = new Bank ();
theBank.readCustomers("src/packageName/customer.txt");
theATM = new ATM (theBank);
}
Hope this helps.
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 :)
im new to methods and classes.
I coded a withdraw/deposit program which ask for name and balance, allowing withdraw and deposit functions. eclipse doesn't allow me to run the program, why is that so?? am I suppose to create (public static void main (string[] args) on a separate class?? and if I have to, what methods(get / set) stay on this class or get transferred to main class?
import java.util.Scanner;
public class bank {
private String name;
private double balance;
private double withdraw;
private double deposit;
private double withdrawTotal;
private double depositTotal;
bank()
{
name = null;
balance = 0;
withdraw = 0;
deposit = 0;
withdrawTotal = 0;
depositTotal = 0;
}
public String getname() {
return name;
}
public double getBalance(){
return balance;
}
//public double getAnnualInterestRate(){
//return annualInterestRate;
//}
public double getWithdraw() {
return withdraw;
}
public double getDeposit() {
return deposit;
}
public double getWithdrawTotal() {
return withdrawTotal;
}
public double getDepositTotal() {
return depositTotal;
}
public void setname(String newname){
Scanner namescan = new Scanner(System.in);
name = namescan.nextLine();
}
public void setBalance(double newBalance){
Scanner bscan = new Scanner(System.in);
balance = bscan.nextInt();
}
public void setWithdraw(double newWithdraw){
withdraw = newWithdraw;
}
public void setDeposit(double newDeposit){
deposit = newDeposit;
}
public void setWithdrawTotal(double newWithdrawTotal){
deposit = newWithdrawTotal;
}
public void setDepositTotal(double newDepositTotal){
deposit = newDepositTotal;
}
//calculate method
public double withdrawCalculuation() {
return balance - withdraw;
}
public double depositCalculation(){
return balance + deposit;
}
//public double annualInterestRateCalculation(){
// return depositTotal * .045;
//}
public void print() {
bank account = new bank();
account.setname(name);
account.setBalance(20000.00);
account.setWithdraw(2500);
account.setWithdrawTotal(17500.00);
account.setDeposit(3000.00);
account.setDepositTotal(20500.00);
//account.setAnnualInterestRate(.045);
System.out.println("The Accound name is:" + account.getname());
System.out.println("The Balance is:" + account.getBalance());
System.out.println("Amount of withdrawal is:" + account.getWithdraw());
System.out.println("The Balance after withdrawal is:" + account.getWithdrawTotal());
System.out.println("Amount of deposit is:" + account.getDeposit());
System.out.println("The Balance after depsoit is:" + account.getDepositTotal());
//System.out.println("The monthly interest for total amount is:" + account.getAnnualInterestRate());
}
}
eclipse doesn't allow me to run the program, why is that so??
Because JVM is not able to find the main() method.
am I suppose to create (public static void main (string[] args) on a separate class??
No. You can add your main() in same class.
Please start with a Basic Java tutorial. You need to have a main method to execute a java program.
Ok, so I hope you can all help, I have been tasked whilst tying to learn the language with the age-old test of simple savings account and checking account using inheritence.
My problem is, I want to make the checking account incapable of going over its overdraft limit and the savings account incapable of going below 0 but cant work out how? my code so far is as follows:
SUPERCLASS (BankAccount):
public class BankAccount
{
protected String CustomerName;
protected String AccountNumber;
protected float Balance;
//Constructor Methods
public BankAccount(String CustomerNameIn, String AccountNumberIn, float BalanceIn)
{
CustomerName = CustomerNameIn;
AccountNumber = AccountNumberIn;
Balance = BalanceIn;
}
// Get name
public String getCustomerName()
{
return (CustomerName);
}
// Get account number
public String getAccountNumber()
{
return (AccountNumber);
}
public float getBalance()
{
return (Balance);
}
public void Withdraw(float WithdrawAmountIn)
{
if(WithdrawAmountIn < 0)
System.out.println("Sorry, you can not withdraw a negative amount, if you wish to withdraw money please use the withdraw method");
else
Balance = Balance - WithdrawAmountIn;
}
public void Deposit(float DepositAmountIn)
{
if(DepositAmountIn < 0)
System.out.println("Sorry, you can not deposit a negative amount, if you wish to withdraw money please use the withdraw method");
else
Balance = Balance + DepositAmountIn;
}
} // End Class BankDetails
SUBCLASS (SavingsAccount):
public class SavingsAccount extends BankAccount
{
private float Interest;
public SavingsAccount(String CustomerNameIn, String AccountNumberIn, float InterestIn, float BalanceIn)
{
super (CustomerNameIn, AccountNumberIn, BalanceIn);
Interest = InterestIn;
}
public float getInterestAmount()
{
return (Interest);
}
public float newBalanceWithInterest()
{
Balance = (getBalance() + (getBalance() * Interest / 100) );
return (Balance);
}
public void SavingsOverdraft()
{
if( Balance < 0)
System.out.println("Sorry, this account is not permitted to have an overdraft facility");
}
}
SUBCLASS (CheckingAccount):
public class CheckingAccount extends BankAccount
{
private float Overdraft;
public CheckingAccount(String CustomerNameIn, String AccountNumberIn, float BalanceIn, float OverdraftIn)
{
super (CustomerNameIn, AccountNumberIn, BalanceIn);
Overdraft = OverdraftIn;
}
public float getOverdraftAmount()
{
return(Overdraft);
}
public void setOverdraft()
{
if (Balance < Overdraft)
System.out.println("Sorry, the overdraft facility on this account cannot exceed £100");
}
}
Thank you very very much for any advice and help!
Add getOverdraftAmount() to your base class:
public int getOverdraftAmount() {
return 0;
}
Then override that method in account subclasses that allow overdrafts. Then revise your logic for withdrawal to take into account that the overdraft limit might not be zero.
public void Withdraw(float WithdrawAmountIn)
{
if(WithdrawAmountIn < 0)
System.out.println("Sorry, you can not withdraw a negative amount, if you wish to withdraw money please use the withdraw method");
else if (Balance - WithdrawAmountIn < -getOverdraftAmount()) {
System.out.println("Sorry, this withdrawal would exceed the overdraft limit");
else
Balance = Balance - WithdrawAmountIn;
}
To do this you will need to override the withdraw function in both the subclasses in order to change the functionality of each individually.
SUBCLASS (SavingsAccount):
public class SavingsAccount extends BankAccount
{
private float Interest;
public SavingsAccount(String CustomerNameIn, String AccountNumberIn, float InterestIn, float BalanceIn)
{
super (CustomerNameIn, AccountNumberIn, BalanceIn);
Interest = InterestIn;
}
public float getInterestAmount()
{
return (Interest);
}
public float newBalanceWithInterest()
{
Balance = (getBalance() + (getBalance() * Interest / 100) );
return (Balance);
}
public void SavingsOverdraft()
{
if( Balance < 0)
System.out.println("Sorry, this account is not permitted to have an overdraft facility");
}
public void Withdraw(float WithdrawAmountIn)
{
if(WithdrawAmountIn < 0)
System.out.println("Sorry, you can not withdraw a negative amount, if you wish to withdraw money please use the withdraw method");
else if (WithdrawAmountIn>Balance)
System.out.println("Sorry, you don't have this much in your account.");
else
Balance = Balance - WithdrawAmountIn;
}
}
SUBCLASS (CheckingAccount):
public class CheckingAccount extends BankAccount
{
private float Overdraft;
public CheckingAccount(String CustomerNameIn, String AccountNumberIn, float BalanceIn, float OverdraftIn)
{
super (CustomerNameIn, AccountNumberIn, BalanceIn);
Overdraft = OverdraftIn;
}
public float getOverdraftAmount()
{
return(Overdraft);
}
public void setOverdraft()
{
if (Balance < Overdraft)
System.out.println("Sorry, the overdraft facility on this account cannot exceed £100");
}
public void Withdraw(float WithdrawAmountIn)
{
if(WithdrawAmountIn < 0)
System.out.println("Sorry, you can not withdraw a negative amount, if you wish to withdraw money please use the withdraw method");
else if (Balance-WithdrawAmountIn<getOverdraftAmount()
System.out.println("Sorry, you cannot withdraw this much");
else
Balance = Balance - WithdrawAmountIn;
}
}