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 :)
Related
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'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 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
}
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())?
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.