Abstract Class/Method Implementation - java

I'm supposed to design a BankAcct class with an abstract method computeIntt(). Save and Time are kinds of BankAcct. The problem is I can't implement the displaying of the Interest and the New balance
Here's my current codes:
public abstract class BankAcct
{
private int accountNumber;
private String accountName;
private double bal;
public BankAcct(int act, String name, double m)
{
accountNumber = act;
accountName = name;
bal = m;
}
public double getBalance()
{
return bal;
}
public String getAccountName()
{
return accountName;
}
public int getAccountNumber()
{
return accountNumber;
}
public void deposit(double m)
{
bal+=m;
}
public void withdraw(double m)
{
bal-=m;
}
public abstract double computeInt();
}
public class Save extends BankAcct
{
public Save(int act, String name, double m)
{
super(act, name, m);
}
int act;
String name="";
double m;
public double computeInt()
{
return m * 0.0025;
}
}
public class Time extends BankAcct
{
public Time(int act, String name, double m)
{
super(act, name, m);
}
int act;
String name="";
double m;
public double computeInt()
{
return m * 0.033;
}
}
public class MainPr
{
public static void main(String[] args)
{
BankAcct sav = new Savings(1234, "ABC", 10000);
BankAcct td = new TimeDeposit(9876, "DEF", 20000);
// display the current balance
System.out.println(sav.getAccountName() + " with account number " +
sav.getAccountNumber() + " has a balance of " +
sav.getBalance());
System.out.println(td.getAccountName() + " with account number " +
td.getAccountNumber() + " has a balance of " +
td.getBalance());
// deposit money
sav.withdraw(5000.0);
// display current value with its interest
System.out.println("\n" + sav.getAccountName() + " with account number " +
sav.getAccountNumber() + " earned an interest of " +
sav.computeInt());
System.out.println(sav.getAccountName() + " with account number " +
sav.getAccountNumber() + " has a NEW BALANCE of " +
sav.getBalance());
td.deposit(2000.0);
System.out.println("\n" + td.getAccountName() + " with account number " +
td.getAccountNumber() + " earned an interest of " +
td.computeInt());
System.out.println(td.getAccountName() + " with account number " +
td.getAccountNumber() + " has a NEW BALANCE of " +
td.getBalance());
}
}
MainPr that will instantiate two objects for the following data:
Save has account number of 1234; account name of ABC; balance of 10,000.
Time has account number of 9876; account name DEF; balance of 20,000.
This should be the output: CORRECT ONE
ABC with account number 1234 has a balance of 10000.0
DEF with account number 9876 has a balance of 20000.0
ABC with account number 1234 earned interest 25.0
ABC with account number 1234 has a NEW balance of 5025.0
DEF with account number 9876 earned interest 660.0
DEF with account number 9876 has a NEW balance of 22660.0
but my program produces the incorrect output:
ABC with account number 1234 has a balance of 10000.0
DEF with account number 9876 has a balance of 20000.0
ABC with account number 1234 earned interest 0.0
ABC with account number 1234 has a NEW balance of 5000.0
DEF with account number 9876 earned interest 0.0
DEF with account number 9876 has a NEW balance of 22000.0
In this case, in Save the interest rate is 0.25% while the interest in time is 3.3% The balance depends whether it is deposit or withdraw.
Kindly help me. thanks

Your instance variables m are always 0 (never initialized) in your subclasses, but they look like they are set to the bal in your BankAcct class. Wouldn't this be appropriate for your computerInterest method in TimeDeposit:
public double computeInterest() {
return getBalance() * 0.033;
}
A similar fix should be provided in the other subclass or at least initialize your m variables. On a related note, your subclasses don't need to define act or name since your superclass BankAcct has it defined and stored already.
Also, your computerInterest isn't modifying your balance, which your program seems to expect. If that's the case, this might be more appropriate:
public double computeInterest() {
double interest = getBalance() * 0.033;
deposit(interest);
return interest;
}

Related

Java inheritance / overriding method ISSUE

okay so to the preface the situation. I have been given an assignment with various tasks. So far I have created a Canteen Account(which will be shown below), a main menu class, and now I have to make another class which inherits from Canteen Account, called StaffAccount. A StaffAccount object should contain the following additional property :
discountRate - the rate (percentage) discount applied to all purchases
A StaffAccount object should contain the following additional methods:
(i) StaffAccount (String newId, String newName, double discountRate)
A constructor method to initialise the StaffAccount object’s properties via the three parameters.
In the staff account I am having issues with a method called PayForMeal(which is an overridden method) which in the assignment brief has the purpose of:
A method to record the cost of a meal. The balance on a StaffAccount object should be amended to reflect discount on the cost of a meal (if the cost does not exceed available balance).
If the cost exceeds the balance then an Exception will be thrown to warn the customer they must topUp their balance – if the customer is within their credit limit a negative value will be recorded in the balance and the status of the account changed to show that the customer is using credit.
No discount should be applied if the customer is using credit.
So my issue is, how do I make a staff account using the constructor given to me, and then use the payForMeal overridden method to apply a discount to the amount a meal costs, then take the discounted amount away from a balance which is not there because it is not in the constructor for the StaffAccount, but it is in the constructor for the CanteenAccount. The classes are below, i just want to know if this is possible or am I being dumb
//////CANTEEN ACCOUNT \\\\\\\\
public class CanteenAcc
{
private String customerId;
private String name;
private double balance;
private static double minTopup = 2.00;
private String status;
private static double creditLimit = 5.00;
private static int transCount;
/**
* Constructor to create a Canteen account object using three parameters
* #param newId - String
* #param newName - String
* #param newBalance - Double
*/
public CanteenAcc(String newId, String newName, double newBalance)
{
this.customerId = newId;
this.name = newName;
this.balance = newBalance;
}
public CanteenAcc(String newId, String newName)
{
this.customerId = newId;
this.name = newName;
}
//BEFORE EVERY METHOD AND CLASS YOU SHOULD HAVE JAVADOC COMMENTS.
public void topUp(double depositAmount)
{
if(depositAmount > 0)
{
this.balance += depositAmount;
this.status = "Valid";
}else
{
this.status = "Invalid";
}
}
public void payForMeal(double amount) throws Exception
{
if(balance - amount < 0 && amount - balance <= creditLimit)
{
this.status = "Using Credit";
double newBalance = balance - amount;
balance = newBalance;
throw new Exception("\n\n-----------------------------\n"
+ "You must top-up your balance\n"
+ "Your new balance is: "+ balance + " GBP" +"\n"
+ "You are: " + status + "\n"
+ "-----------------------------\n");
}
else if(amount > creditLimit && balance < amount)
{
throw new Exception("\n\n------------------------------\n"
+ "Cost exceeds the credit limit."
+ "\n------------------------------\n");
}
else
{
double newBalance = balance - amount;
balance = newBalance;
transCount++;
}
}
public String displayAccountDetails()
{
StringBuilder ad = new StringBuilder();
ad.append("------------------------\n");
ad.append("****Account Details****\n");
ad.append("------------------------\n");
ad.append("\n");
ad.append("****Customer ID****: \n" + customerId + "\n");
ad.append("\n");
ad.append("****Name****: \n" + name + "\n");
ad.append("------------------------\n");
ad.append("\n");
return ad.toString();
}
public String getStatistics()
{
StringBuilder as = new StringBuilder();
as.append("------------------------\n");
as.append(" CANTEEN ACCOUNT \n");
as.append("------------------------\n");
as.append("\n");
as.append("****Transaction Count****\n");
as.append(transCount + "\n");
as.append("\n");
as.append("****Account Balance****\n");
as.append(balance + "\n");
as.append("\n");
as.append("***Account Status****\n");
as.append(status + "\n");
as.append("------------------------\n");
return as.toString();
}
public double getBalance()
{
return balance;
}
public double getCreditLimt()
{
return creditLimit;
}
public double getMinTopup()
{
return minTopup;
}
public String getStatus()
{
return status;
}
public static void updateCreditLimit(double newLimit)
{
creditLimit = newLimit;
}
public static void updateMinTopup(double newTopup)
{
minTopup = newTopup;
}
}
////////MAIN METHOD////////////////////////
public class Test
{
public static void main(String[] args) {
String menuItems[] = {"1. Top up account ", "2. Pay for meal ", "3. Display Account Status",
"4. Display Account Balance ", "5. Display Account Details ",
"6. Update credit limit ", "7. Update Minimum top-up ", "8. Exit program"};
Menu myMenu = new Menu("Holiday Account", menuItems) ;
int choice;
Scanner keyb = new Scanner(System.in);
choice = myMenu.getChoice() ;
do{
choice = myMenu.getChoice();
//CanteenAcc Employee = new CanteenAcc("A01PL", "Patrick", 2);
CanteenAcc Employee2 = new StaffAccount("blah", "blah", 0.25);
switch (choice)
{
case 1 : System.out.println("How much would you like to top-up: ");
double deposit = keyb.nextDouble();
Employee2.topUp(deposit);
System.out.println("Your balance is: £" + Employee2.getBalance());
break ;
case 2: System.out.println("Input how much your meal costs: ");
try {
double amount = keyb.nextDouble();
Employee2.payForMeal(amount);
System.out.println("Your meal cost: " + amount);
} catch(Exception ex)
{
System.out.println(ex.toString());
}
System.out.println("Your balance is: £" + Employee2.getBalance());
break ;
case 3: System.out.println(Employee2.getStatus());
break;
case 4: System.out.println("£" + Employee2.getBalance());
break;
case 5: System.out.println(Employee.displayAccountDetails());
break;
case 6: System.out.println("What amount would you like the new limit to be: ");
double newLimit = keyb.nextDouble();
CanteenAcc.updateCreditLimit(newLimit);
System.out.println("The new credit limit is: " + newLimit);
case 7: System.out.println("What amount would you like the new limit to be: ");
double newMinTopup = keyb.nextDouble();
CanteenAcc.updateMinTopup(newMinTopup);
System.out.println("The new minimum topUp is: " + newMinTopup);
case 8: System.exit(0);
}
}//End DoWhile
while(choice != 8);
}
}
////STAFF ACCOUNT///////
public class StaffAccount extends CanteenAcc
{
private double discountRate;
public StaffAccount(String newId, String newName, double discountRate)
{
super (newId, newName);
this.discountRate = 0.25;
balance = 0;
}
public void setDiscountRate(double rate)
{
discountRate = rate;
}
public double getDiscountRate()
{
return discountRate;
}
public void payForMeal(double amount) throws Exception
{
amount = amount/discountRate;
super.payForMeal(amount);
}
}
OK:
You've got a CanteenAcc: good. You've also got a StaffAccount that inherits from CanteenAcc. Also good.
You should annotate StaffAccount.payForMeal() with #Override: When do you use Java's #Override annotation and why?
Your variable names should all start with lower case, e.g. CanteenAcc employee2 = new StaffAccount("blah", "blah", 0.25);.
updateCreditLimit() and updateMinTopup() should NOT be static (because each different object might have a different value): Java: when to use static methods
... Finally ...
With CanteenAcc employee = new CanteenAcc("A01PL", "Patrick", 2);, then employee.payForMeal() will have the "CanteenAcc" behavior.
With CanteenAcc employee2 = new StaffAccount("blah", "blah", 0.25);, then employee2.payForMeal() will have the "StaffAccount" behavior.
Q: So what's the problem? Does that help clarify ... or does it just confuse things further?
There are a number of things "wrong" with the code you posted. I hope you have an IDE, and step through the debugger with sample test values.
But to your original question:
You're on the right track.
There are a couple of "minor" issues I noted above.
I'm not sure why you're worried about "constructors". The way object oriented languages (like Java) work - if you define the right base classes, and appropriately "specialize" behavior in subclasses, then - through the magic of "inheritence" - everything "just works".
I modified your code slightly, and wrote a different "test driver". Here is the code, and the output:
StaffAccount.java
package com.example;
public class StaffAccount extends CanteenAccount {
private double discountRate;
public StaffAccount(String newId, String newName, double discountRate) {
super(newId, newName);
this.discountRate = discountRate; // Set this to "discountRate", instead of hard-coding 0.25
// You'll note that "balance" is implicitly set to "0.0" in the base class
}
public void setDiscountRate(double rate) {
discountRate = rate;
}
public double getDiscountRate() {
return discountRate;
}
#Override
public void payForMeal(double amount) throws Exception {
amount = amount / discountRate;
super.payForMeal(amount);
}
}
TestAccount.java
package com.example;
/**
* Test driver
* In a "real" application, I would implement these as a suite of JUnit tests
*/
public class TestAccount {
private static void buyAMeal (CanteenAccount person, double cost) {
try {
person.payForMeal(cost);
} catch (Exception e) {
System.out.println ("ERROR: " + e.getMessage());
}
}
public static void main(String[] args) {
System.out.println (">>Creating employee (\"CanteenAccount\" and employee2 (\"StaffAccount\") objects...");
CanteenAccount employee = new CanteenAccount("A01PL", "Patrick", 2);
CanteenAccount employee2 = new StaffAccount("blah", "blah", 0.25);
System.out.println (">>Checking initial balances...");
System.out.println (" employee balance=" + employee.getBalance() + ", creditLimit=" + employee.getCreditLimit());
System.out.println (" employee2 balance=" + employee2.getBalance() + ", creditLimit=" + employee2.getCreditLimit());
System.out.println (">>Buying a $5.00 meal...");
System.out.println (" employee...");
buyAMeal (employee, 5.00);
System.out.println (" employee balance=" + employee.getBalance() + ", creditLimit=" + employee.getCreditLimit());
System.out.println (" employee2...");
buyAMeal (employee2, 5.00);
System.out.println (" employee2 balance=" + employee2.getBalance() + ", creditLimit=" + employee2.getCreditLimit());
System.out.println (">>Add $5.00 and buy another $5.00 meal...");
System.out.println (" employee...");
employee.topUp(5.0);
buyAMeal (employee, 5.00);
System.out.println (" employee balance=" + employee.getBalance() + ", creditLimit=" + employee.getCreditLimit());
System.out.println (" employee2...");
employee2.topUp(5.0);
buyAMeal (employee2, 5.00);
System.out.println (" employee2 balance=" + employee2.getBalance() + ", creditLimit=" + employee2.getCreditLimit());
}
}
Sample output:
>>Creating employee ("CanteenAccount" and employee2 ("StaffAccount") objects...
>>Checking initial balances...
employee balance=2.0, creditLimit=5.0
employee2 balance=0.0, creditLimit=5.0
>>Buying a $5.00 meal...
employee...
ERROR:
-----------------------------
You must top-up your balance
Your new balance is: -3.0 GBP
You are: Using Credit
-----------------------------
employee balance=-3.0, creditLimit=5.0
employee2...
ERROR:
------------------------------
Cost exceeds the credit limit.
------------------------------
employee2 balance=0.0, creditLimit=5.0
>>Add $5.00 and buy another $5.00 meal...
employee...
ERROR:
-----------------------------
You must top-up your balance
Your new balance is: -3.0 GBP
You are: Using Credit
-----------------------------
employee balance=-3.0, creditLimit=5.0
employee2...
ERROR:
------------------------------
Cost exceeds the credit limit.
------------------------------
employee2 balance=5.0, creditLimit=5.0

NetBeans : Trying to create a class file to work with another program

Having trouble compiling these two files to run together.
I get a "can't find or load main class" error or a "erroneous tree" error.
Never asked for help on here before, hope this works :)
package savingsaccount;
import java.util.Scanner;
public class SavingsAccount
{
public static void main(String[] args)
{
double begginingBalance, deposit, withdraw;
int months;
double monthlyRate;
double plus = 0.0;
double minus = 0.0;
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter the balance at beggining of " +
"accounting period.");
begginingBalance = keyboard.nextDouble();
System.out.println("Please enter number of months in current " +
"accounting period.");
months = keyboard.nextInt();
System.out.println("Enter the annual interest rate.");
monthlyRate = keyboard.nextDouble();
a7main accounting = new a7main();
for(int month = 1; month<=months; month++)
{
System.out.println("Enter the amount of deposits for month " +
month + " : ");
plus = keyboard.nextDouble();
accounting.deposits(plus);
System.out.println("Enter the amount of withdrawals for" +
" month " + month + ": ");
minus = keyboard.nextDouble();
accounting.withdrawals(minus);
accounting.interest(monthlyRate);
}
System.out.println("The account balance is: " +
accounting.getBalance());
System.out.println("The total amount of deposits is:" + plus);
System.out.println("The total amount of withdrwals is: " + minus);
System.out.println("The earned interest is: " +
accounting.getRate());
}
}
HERE IS THE CLASS FILE
I am trying to use the methods in this file to calculate and hold the values from the other file.
public class a7main
{
private double totalBalance;
private double interestRate;
public a7main(double balance,double rate)
{
totalBalance = balance;
interestRate = rate;
}
public void deposits(double deposit)
{
totalBalance = totalBalance+deposit;
}
public void withdrawals(double withdraw)
{
totalBalance = totalBalance-withdraw;
}
public void interest(double rate)
{
interestRate = totalBalance*rate;
}
public double getBalance()
{
return totalBalance;
}
public double getRate()
{
return interestRate;
}
}
#Alex Goad -
Add package name in a7main class
You have created parameterized constructor and no default constructor.
a7main accounting = new a7main();
The above line will look for default constructor like
public a7main(){
}

Object oriented programming, getter is not getting private variable from another class

The program is supposed to calculate interest for 2 accounts after 12 and 24 months. This works fine. My issue is the getter/setter for interest rate do not work, so when the interest rate is saved as 0.1 in another class private variable I can't print it from main class.
public class testAccountIntrest{
//main method
public static void main(String[] args) {
//creating objects
Account account1 = new Account(500);
Account account2 = new Account(100);
//printing data
System.out.println("");
System.out.println("The intrest paid on account 1 after 12 months is " + account1.computeIntrest(12));
System.out.println("");
System.out.println("The intrest paid on account 1 after 24 months is " + account1.computeIntrest(24));
System.out.println("");
System.out.println("");
System.out.println("The intrest paid on account 2 after 12 months is " + account2.computeIntrest(12));
System.out.println("");
System.out.println("The intrest paid on account 2 after 24 months is " + account2.computeIntrest(24));
System.out.println("");
System.out.println("The intrest rate is " + getIntrest());
}//end main method
}//end main class
class Account {
//instance variables
private double balance;
private double intrestRate = 0.1;
//constructor
public Account(double initialBalance) {
balance = initialBalance;
}
//instance methods
public void withdraw(double amount) {
balance -= amount;
}
public void deposit(double amount) {
balance += amount;
}
public double getBalance() {
return balance;
}
public void setIntrest(double rate) {
intrestRate = rate;
}
public double getIntrest() {
return intrestRate;
}
public int computeIntrest(int n) {
double intrest = balance*Math.pow((1+intrestRate),(n/12));
return (int)intrest;
}
}
As the compiler is undoubtedly telling you, your testAccountIntrest class doesn't have a method called getInterest(). So this alone can't do anything in the context of that class:
getInterest()
However, your Account class does have that method. And you have two Account objects in that scope:
Account account1 = new Account(500);
Account account2 = new Account(100);
So you can call that method on those objects:
account1.getInterest()
or:
account2.getInterest()
Basically, you have to tell the code which object you're calling the method on. It can't figure it out on its own.
getIntrest() is a member method, therefore you need to call
System.out.println("The intrest rate for account 1 is " + account1.getIntrest());
System.out.println("The intrest rate for account 2 is " + account2.getIntrest());
To call a method from another class you need an object of another class.
So, you need an instance of account to call getIntrest. For example:
System.out.println("The intrest rate for account 1 is " + account1.getIntrest());
If an interest rate is the same for all accounts you can make it static:
private static double intrestRate = 0.1;
public static double getIntrest() {
return intrestRate;
}
Static fields belong to the class and you don't need a specific instance to access it:
System.out.println("The intrest rate for all accounts is " + Account.getIntrest());

Bank Account TransferTo Method

Ok I am having problems creating a transfer to method to transfer "money" from one account to the next. After the transfer the amounts of each account would be printed out. I created the code but when I run it the amount transferred is set to the bank account amount. It should just deduct from one account and add to the next account. What am I doing wrong?
This is my class with contructors and methods:
public class Account {
// Instance variables
private double balance;
// Constructors
public Account(double initialBalance) {
balance = initialBalance;
}
public Account(int account, double balance) {
this.balance = balance;
}
public Account() {
balance = 0.0;
}
// Instance methods
public void setBalance() {
balance = Math.random() * 1000;
balance = Math.round((balance * 100.0)+.5) / 100.0;
}
public void deposit(double amount) {
balance = balance + amount;
}
public void withdraw(double amount) {
balance = balance - amount;
}
public double getBalance() {
balance = Math.round((balance * 100.0)+.5) / 100.0;
return balance;
}
public void close() {
balance = 0.0;
}
public void transferTo(Account bank, double x) {
if (x <= balance) {
withdraw(x);
bank.deposit(x);
System.out.println("\nTransfer succesful. Tansfered: $" + bank.getBalance());
} else if (x > balance) {
System.out.println("\nTransfer failed, not enough balance!");
}
}
}
This is my class with the main method
public class MyBank {
public static void main(String[] args) {
Account[] bank = { new Account(), new Account(), new Account(),
new Account() };
bank[0].setBalance();
bank[1].setBalance();
bank[2].setBalance();
bank[3].setBalance();
System.out.println("Accounts 1 balance is: $" + bank[0].getBalance());
System.out.println("Accounts 2 balance is: $" + bank[1].getBalance());
System.out.println("Accounts 3 balance is: $" + bank[2].getBalance());
System.out.println("Accounts 4 balance is: $" + bank[3].getBalance());
double x = Math.random()*100;
bank[0].transferTo(bank[1], x);
System.out.println("Remaining balance of Account 1: $" + bank[0].getBalance());
System.out.println("Remaining balance of Account 2: $" + bank[1].getBalance());
double y = (Math.random()*300);
bank[2].transferTo(bank[3], y);
System.out.println("Remaining balance of Account 3: $" + bank[2].getBalance());
System.out.println("Remaining balance of Account 4: $" + bank[3].getBalance());
}
}
One issue you did have, is that you were accidentally printing the BALANCE rather than the amount actually transferred, in your transferTo() method. I fixed this. On another note, if you're going to be printing these numbers out, look into printf() to make them appear as actual dollar amounts. I did it to one of the lines to show you an example.
PS - Try NOT using Math.random() for stuff when you're trying to debug.
public void transferTo(Account bank, double x) {
if (x <= this.balance) {
withdraw(x);
bank.deposit(x);
System.out.println("\nTransfer succesful. Tansfered: $" + x);
} else { //does not need to be else if, because if not <=, it MUST be >.
System.out.println("\nTransfer failed, not enough balance!");
}
}
I can verify that the method works perfectly fine, after these edits, on my machine. This is what I used to test:
public class MyBank {
public static void main(String[] args) {
Account[] bank = { new Account(), new Account(), new Account(),
new Account() };
bank[0].setBalance();
bank[1].setBalance();
bank[2].setBalance();
bank[3].setBalance();
double x = 100.00;
System.out.printf("Transferring $%.2f from Acc 1 to Acc 2.\n", x); //printf example
System.out.println("Acc 1 previous balance: " + bank[0].getBalance());
System.out.println("Acc 2 previous balance: " + bank[1].getBalance());
bank[0].transferTo(bank[1], x);
System.out.println("Acc 1 new balance: " + bank[0].getBalance());
System.out.println("Acc 2 new balance: " + bank[1].getBalance());
}
}
And lastly, my output:
Transferring $100.00 from Acc 1 to Acc 2.
Acc 1 previous balance: 106.76
Acc 2 previous balance: 266.18
Transfer succesful. Transfered: $100.0
Acc 1 new balance: 6.77
Acc 2 new balance: 366.19
System.out.println("\nTransfer succesful. Tansfered: $" + bank.getBalance());
This prints the other account's new balance, because that's what you told it to do.
If you want to print the amount transferred:
System.out.println("\nTransfer succesful. Tansfered: $" + x);
// Bank account class
class BankAccount {
constructor(fname, lname, account_number) {
const minBalance = 10000;
this.name = `${fname} ${lname}`;
this.balance = minBalance;
this.account_number = account_number;
}
details() {
console.log(
`Cleint name: ${this.name} \n Balance: ${this.balance} \n Account number: ${this.account_number}`
);
}
isPositive(amount) {
return amount > 0 ? true : false;
}
isVlaidAmount(amount) {
return isNaN(amount) || !this.isPositive(amount) ? false : true;
}
deposit(amount) {
if (this.isVlaidAmount(amount)) {
this.balance += amount;
} else {
console.log("Sorry, this transcation cannot be completed!");
}
}
withdraw(amount) {
if (this.isVlaidAmount(amount)) {
this.balance -= amount;
} else {
console.log("Sorry, you have insufficient funds.");
}
}
transfer(amount, reciever) {
if (this.isVlaidAmount(amount)) {
this.withdraw(amount);
reciever.deposit(amount);
}
}
}
// create objects
let acc1 = new BankAccount("George", "Omara", 422);
let acc2 = new BankAccount("Haward", "Walowets", 662);

Bank Account Program Issue

For my Java class, we need to make a bank account that has the methods of withdrawing, depositing money, and displaying current balance. In the Tester class, I want to make it ask for the name, the balance, then allow you to choose 1, 2, or 3. Then it repeats the option you choose until you say type "n". The problem is that running this code causes it to say after you deposit money "You deposited (amount of money deposited) in the account (name of account). Your new balance is (this)." The part where it says "this" is the exact same of the amount of money deposited. In other words, it doesn't add it, it just makes the new balance the same as the deposit, regardless of how much was in before. Any help? Thanks.
import java.io.*;
import java.util.*;
public class BankAccount
{
public BankAccount(double b, String n)
{
double balance = b;
String name = n;
}
public void deposit(double d)
{
balance += d;
}
public void withdraw(double w)
{
balance -= w;
}
public String nickname()
{
System.out.print("Enter a new name: ");
Scanner kbIn = new Scanner(System.in);
String n = kbIn.nextLine();
return n;
}
double balance;
String name;
}
And the tester class:
import java.io.*;
import java.util.*;
public class Tester
{
public static void main(String args[])
{
Scanner kbInLine = new Scanner(System.in);
Scanner kbIn = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = kbInLine.nextLine();
System.out.print("Please enter balance: $");
double balance = kbIn.nextDouble();
BankAccount myAccount = new BankAccount(balance, name);
String proceed = "y";
while(proceed.equalsIgnoreCase("y"))
{
System.out.println("\nPlease pick a number. Would you like to...\n\t 1. Deposit\n\t 2. Withdraw\n\t 3. Print Balance\n");
int choice = kbIn.nextInt();
switch(choice)
{
case 1:
System.out.print("How much would you like to deposit?\n\t$");
double deposit = kbIn.nextDouble();
myAccount.deposit(deposit);
System.out.println("You have deposited $" + deposit + " into the account of " + name + ". The new balance is: " + myAccount.balance);
break;
case 2:
System.out.print("How much would you like to withdraw?\n\t$");
double withdraw = kbIn.nextDouble();
if(myAccount.balance - withdraw > 0)
{
myAccount.withdraw(withdraw);
System.out.println("You have withdrawn $" + withdraw + " from the account of " + name + ". The new balance is: " + myAccount.balance);
}
else
{
System.out.println("Sorry, you have insufficient funds for this operation. Your existing balance is $" + myAccount.balance);
}
break;
case 3:
System.out.print("The balance in the account of " + name + " is $" + myAccount.balance);
break;
}
System.out.print("\nWould you like to do another transaction? (Y/N)");
proceed = kbIn.next();
}
System.out.println("\nThank you for banking with us. Have a good day!");
}
}
What's really wierd is that I did a project before this one (it's actually a simplified version) where it deposits and then withdraws a predetermined, coded amount, then outputs the new bank balance, and it does it fine. But the code for BankBalance is the same. Here's the code for those.
BankAccount class is:
public class BankAccount
{
public BankAccount(String nm, double amt) // Constructor
{
name = nm;
balance = amt;
}
public void deposit(double d) // Sets up deposit object as balance += d
{
balance += d;
}
public void withdraw(double w) // Sets up withdraw object as balance -= w
{
balance -= w;
}
public double balance;
public String name;
}
And the Tester class is:
import java.io.*;
import java.util.*;
public class Tester
{
public static void main(String args[])
{
Scanner kbIn = new Scanner(System.in);
System.out.print("Enter your name:");
String name = kbIn.nextLine();
System.out.print("Enter the balance:");
double balance = kbIn.nextDouble();
BankAccount myAccount = new BankAccount(name, balance);
myAccount.deposit(505.22);
System.out.println(myAccount.balance);
myAccount.withdraw(100.00);
System.out.println("The " + myAccount.name + " account balance is, $" + myAccount.balance);
}
}
You're not actually initialising your balance member variable here:
public BankAccount(double b, String n)
{
double balance = b;
This creates a new local variable called balance, to which you assign the value of b. The member variable balance will remain 0 (the default) after this constructor is run.
public BankAccount(double b, String n)
{
double balance = b;
String name = n;
}
--->
public BankAccount(double b, String n)
{
this.balance = b;
this.name = n;
}
Or you can declare balance as static (data class field), and the methods that use this variable as static too.

Categories

Resources