Java inheritance / overriding method ISSUE - java

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

Related

How to fix return values not show up on one of my method

I tried to return values from two of my 4 methods so I can use print out on my final methods. The return value doesn't show up and my results were null and 0.0.
import java.util.*;
public class payroll {
static Scanner console = new Scanner(System.in);
static double hour;
static String employee;
static double rate;
static double gross_pay;
static double tax;
static double deduction;
static double net_pay;
public static void main(String[] args) {
name();
number(hour, rate, tax, gross_pay, deduction, net_pay);
print();
}
public static String name() {
System.out.print("Please enter employee's name: ");
String employee = console.nextLine();
return employee;
}
public static double[] number(double hour, double rate, double tax, double gross_pay, double deduction, double net_pay) {
double[] pay = new double[7];
pay[1] = hour;
pay[2] = rate;
pay[3] = tax;
pay[4] = gross_pay;
pay[5] = deduction;
pay[6] = net_pay;
System.out.print("Please enter number of hours worked: ");
pay[1] = console.nextDouble();
System.out.print("Please enter rate of pay: ");
pay[2] = console.nextDouble();
System.out.print("Please enter federal tax rate: ");
pay[3] = console.nextDouble();
pay[4]= hour*rate;
pay[5] = gross_pay*tax;
pay[6] = gross_pay-deduction;
return pay;
}
public static void print() {
System.out.printf("Employee's Name: " + employee + "\n" +
"Hours Worked: " + hour + "\n" +
"Hourly Pay: " + rate + "\n" +
"Gross Pay: " + gross_pay + "\n" +
"Tax Deducted: " + deduction + "\n" +
"Net Pay: " + net_pay);
}
}
The expected results are the name of the employee and the calculations made in the methods.
The issue here is that you are not assigning the return value to anything.
Normally you would do something like
employee = name();
But other points to mention is that you have employee etc declared as fields, so they are directly accessible via the methods
e.g.
public static void name() { // do not return any thing
System.out.print("Please enter employee's name: ");
// do not de-declare, just use the field
employee = console.nextLine();
}
This would be correct to use, as you are not passing any parameters to print and are printing out the values of the fields

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(){
}

How to create an equals Method in Java for 2 credit cards

so I'm having an issue writing my code such that i will be able to create an equals method that will return true if 2 credit cards are equal if they have the same Security code, company and account number.
Heres my code so far.
public class CreditCard {
private double balance;
public static double interestRate;
public static String personname;
public static String company;
public static double creditLine;
public CreditCard ()
{
balance = 0;
}
public static void setIntRate (double rate)
{
interestRate = rate;
System.out.println("The Interest rate for this card is : " + interestRate);
}
public static double getIntRate ()
{
return interestRate;
}
public static void setPersonName (CreditCard card ,String pName)
{
personname = pName;
System.out.println("Name on card: " + personname);
}
public static void setCompany (CreditCard card, String compName)
{
company =compName;
System.out.println("The Company name is : "+ company);
}
//creates new card number
public static void CardNum (CreditCard card)
{
int[] accountnumber = new int [16];
Random generator = new Random ();
for (int i =0; i<16; i++)
accountnumber [i] = (int)(Math.random()*10);
System.out.println ("The Account number for this card is: " + (java.util.Arrays.toString(accountnumber))+"");
}
//Creates new securitycode
public static void getSecurityCode (CreditCard card)
{
int[] securitycode = new int [3];
Random generator = new Random ();
for (int i =0; i<3; i++)
securitycode [i] = (int)(Math.random()*10);
System.out.println ("The security code for this card is: " + (java.util.Arrays.toString(securitycode))+"");
}
public static void setexpirationdate(int MM, int YY)
{
System.out.println("The expiration date for this card is: " + MM + "/"+ YY + "\n");
}
public static void setCreditLine (int cLine){
creditLine =cLine;
}
public static void getCreditLine (CreditCard card)
{
System.out.println( " CreditLine is : $" + creditLine);
}
// buys something
public void buyWithCreditCard (double amount)
{
balance = balance + amount;
}
//Inserts money to reduce balance
public double paybalance (double amount)
{
if (balance >= amount){
balance = balance - amount;
roundBalance();}
else{
creditLine = creditLine + (amount - balance);
balance = 0;
System.out.println("Your new CreditLine is: "+creditLine);
roundBalance();
}
return amount;
}
// adds interest to balance
public void addInterest ()
{
double interest = balance * getIntRate ();
balance = balance + interest;
roundBalance ();
}
private void roundBalance ()
{
balance = (double)(Math.round(balance*100))/100;
}
public double checkBalance (){
return balance;
}
//Shows Credit Card Debt
public static void showBalance (CreditCard card)
{
System.out.print(card.balance);
}
}
and then the class that utilizes the CreditCard Class.
public class CreditCardDemo {
public static void main (String [] args)
{
//Creates cards 1 and 2
CreditCard firstCard = new CreditCard ();
CreditCard secondCard = new CreditCard ();
//Calls for card info 1
System.out.println("First card Information is:");
CreditCard.setPersonName(firstCard,"John White");
//CreditCard.getName(firstCard);
CreditCard.setCreditLine(600);
CreditCard.getCreditLine(firstCard);
CreditCard.setCompany(firstCard,"Visa");
CreditCard.setIntRate(0.02);
CreditCard.CardNum(firstCard);
CreditCard.getSecurityCode(firstCard);
CreditCard.setexpirationdate(11, 17);
//call for card info 2
System.out.println("Second card Information is:");
CreditCard.setPersonName(secondCard,"Jack Black");
CreditCard.setCreditLine(2600);
CreditCard.getCreditLine(secondCard);
//CreditCard.getName(secondCard);
CreditCard.setCompany(secondCard,"Discover");
CreditCard.setIntRate(0.02);
CreditCard.CardNum(secondCard);
CreditCard.getSecurityCode(secondCard);
CreditCard.setexpirationdate(10, 19);
//Purchases
System.out.println("\nYou bought something for $5.00");
firstCard.buyWithCreditCard (5.00);
System.out.println("You bought another item for $12.00");
firstCard.buyWithCreditCard(12.00);
System.out.println("You bought another item for $15.00");
firstCard.buyWithCreditCard(15.00);
System.out.println("You bought another item for $33.42");
firstCard.buyWithCreditCard(33.42);
//Display Current Balance
System.out.print("You currently owe: $");
CreditCard.showBalance(firstCard);
//Interest Adds onto it
if (firstCard.checkBalance () > 50.00){
System.out.println("\nInterest has been added");
firstCard.addInterest ();
System.out.print("Your new balance is : $");
CreditCard.showBalance(firstCard);
System.out.println("");
//Payment
System.out.println("You have overpaid your balance.");
firstCard.paybalance (70);
System.out.print("Your new balance is : $");
CreditCard.showBalance(firstCard);
}
}
}
So if anyone could show me how to create a method in the CreditCard class that would allow me to check if the firstCard and secondCard, that would be great. Thanks a bunch :)
If you use NetBeans, you can simply auto-generate the equals function (not sure about Eclipse). Other than that it boils down to overwriting the equals function of Object.
Make sure to check that both are of the same class and make sure to check for null. Java recommends to as well overwrite the hashCode function, however that depends on your use-case.
first of all, i'm not that advanced in java, but this seems simple enough still.
The problem here seems that the security code is never saved (the method getSecurityCode is void and all variables are only local)
Same goes for the company
nonetheless, here's an example, assuming you fixed that and made a method getCode that returns the code (as int) and a method getAccountNumber, that returns that number (as int). (and assuming it's no problem to make those methods public)
public boolean equals(CreditCard creditCard1, CreditCard creditCard2){
if (creditCard1 == null || creditCard2 == null)
return creditCard1 == creditCard2;
boolean equalCode = (creditCard1.getCode() == creditCard2.getCode());
boolean equalCompany = creditCard1.company.equals(creditCard2.company);
boolean equalAccountNumber = (creditCard1.getAccountNumber() == creditCard2.getAccountNumber());
return equalCode && equalCompany && equalAccountNumber;
}
It would be good practice to make the variables private and make some getters, but that's up to you.

Abstract Class/Method Implementation

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;
}

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